.NET Core 3 Web Api Cors fetch 一直 307 Temporary Redirect
.NET Core 3 Web Api Cors fetch 一直 307 Temporary Redirect
继上一篇 .net core 3 web api jwt 一直 401 为添加JWT-BearerToken认证所述的坑后,
本次为添加CORS跨域,又踩坑了。
自从 .NET Core 2.2 之后,CORS跨域配置代码发生了很大变化。
在 .NET Core 3.1 中,本作者碰到各种HTTP错误,诸如 500、307、401 等错误代码...
在必应Bing和不断Debug调整配置代码位置后,得知:
AllowAnyOrigin方法,在新的 CORS 中间件已经被阻止使用允许任意 Origin,所以该方法无效。AllowCredentials方法,自从 .NET Core 2.2 之后,不允许和AllowAnyOrigin同时调用。WithOrigins方法,在 .NET Core 3.1 中有bug,具体原因未知,暂时只能用SetIsOriginAllowed(t=> true)代替,等效.AllowAnyOrigin方法。- 创建项目默认的模板中,
app.UseHttpsRedirection()在前面,所以我将app.UseCors()放在它后面,这是导致HTTP 307 Temporary Redirect福报的根本原因之一。 - 度娘告诉我,
app.UseCors()方法要在app.UseAuthentication()之后,是误人子弟的,其实放在它前面也可以,并且app.UseCors()要在app.UseRouting()之后,app.UseEndpoints()和app.UseHttpsRedirection()之前 - 使用fetch跨域请求时,要注意controller的action是否有设置除了
HttpOptions之外的其它Http Method方法,如果有要加上HttpOptions标记特性,因为fetch跨域请求会先执行OPTIONS预请求。 - 使用fetch请求需要JWT认证的接口时,除了在HTTP Headers设置
Authorization之外,还需要设置'credentials': 'include'。 - 写
app.UseXxxxxx方法,引入中间件时,要注意管道(Middleware)注册顺序。
参考:
- CORS配置:https://docs.microsoft.com/zh-cn/aspnet/core/security/cors?view=aspnetcore-3.1
- JWT认证:https://docs.microsoft.com/zh-cn/aspnet/core/security/authentication/?view=aspnetcore-3.1
- Cors Issue: https://github.com/dotnet/aspnetcore/issues/16672
- Forum: https://forums.asp.net/t/2160821.aspx?CORS+in+ASP+NET+Core+3+x
源代码
以下是在 .NET Core 3.1下经过严谨测试,可以JWT认证、CORS跨域、IIS托管、自寄主运行的源代码,仅供参考。
WebApi.csproj
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<RootNamespace>WebApi</RootNamespace>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="3.1.2" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="3.1.2" />
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="3.1.2" />
<PackageReference Include="Microsoft.Extensions.Logging.EventSource" Version="3.1.2" />
<PackageReference Include="Microsoft.Extensions.Logging.TraceSource" Version="3.1.2" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="3.1.2" />
<PackageReference Include="Microsoft.TeamFoundationServer.Client" Version="16.153.0" />
<PackageReference Include="Microsoft.VisualStudio.Services.Client" Version="16.153.0" />
<PackageReference Include="Microsoft.VisualStudio.Services.InteractiveClient" Version="16.153.0" />
<PackageReference Include="NLog.Web.AspNetCore" Version="4.9.0" />
</ItemGroup>
</Project>
Program.cs
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using System.Diagnostics;
using System.IO;
namespace WebApi
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args)
{
return Host.CreateDefaultBuilder(args)
.ConfigureLogging((context, logging) =>
{
logging.ClearProviders()
#if DEBUG
.AddConsole()
.AddDebug()
.AddEventLog()
.AddTraceSource(new SourceSwitch(nameof(Program), "Warning"), new ConsoleTraceListener())
#endif
.AddNLog();
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseContentRoot(Directory.GetCurrentDirectory())
.UseKestrel()
.UseIISIntegration()
.UseIIS()
.UseStartup<Startup>();
});
}
}
}
Startup.cs
using MCS.Vsts.Options;
using MCS.Vsts.Services;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.IdentityModel.Tokens;
using System.Text;
namespace WebApi
{
public class Startup
{
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
//认证
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
var secretBytes = Encoding.UTF8.GetBytes(Configuration["ServerConfig:Secret"]);
options.TokenValidationParameters = new TokenValidationParameters()
{
IssuerSigningKey = new SymmetricSecurityKey(secretBytes),
ValidateIssuer = false,
ValidateAudience = false,
ValidateActor = false,
RequireSignedTokens = true,
RequireExpirationTime = true,
ValidateLifetime = true
};
});
//跨域
services.AddCors(options =>
{
options.AddDefaultPolicy(builder =>
{
builder
//允许任何来源的主机访问
//TODO: 新的 CORS 中间件已经阻止允许任意 Origin,即设置 AllowAnyOrigin 也不会生效
//AllowAnyOrigin()
//设置允许访问的域
//TODO: 目前.NET Core 3.1 有 bug, 暂时通过 SetIsOriginAllowed 解决
//.WithOrigins(Configuration["CorsConfig:Origin"])
.SetIsOriginAllowed(t=> true)
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
});
});
//TODO: do something...
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
//Enabled HSTS
app.UseHsts();
}
//TODO: 要放在UseCors之后
//app.UseHttpsRedirection();
app.UseRouting();
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
});
//TODO: UseCors要在UseRouting之后,UseEndpoints 和 UseHttpsRedirection 之前
app.UseCors();
app.UseAuthentication();
app.UseAuthorization();
app.UseHttpsRedirection();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
appsettings.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"https_port": 44370,
"urls": "http://*:50867",
"ServerConfig": {
"Secret": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
},
"CorsConfig": {
"BaseUri": "http://myserver"
}
}
.NET Core 3 Web Api Cors fetch 一直 307 Temporary Redirect的更多相关文章
- angular4和asp.net core 2 web api
angular4和asp.net core 2 web api 这是一篇学习笔记. angular 5 正式版都快出了, 不过主要是性能升级. 我认为angular 4还是很适合企业的, 就像.net ...
- .net core 3 web api jwt 一直 401
最近在给客户开发 Azure DevOps Exension, 该扩展中某个功能需要调用使用 .NET Core 3 写的 Web Api. 在拜读了 Authenticating requests ...
- 温故知新,使用ASP.NET Core创建Web API,永远第一次
ASP.NET Core简介 ASP.NET Core是一个跨平台的高性能开源框架,用于生成启用云且连接Internet的新式应用. 使用ASP.NET Core,您可以: 生成Web应用和服务.物联 ...
- 使用angular4和asp.net core 2 web api做个练习项目(一)
这是一篇学习笔记. angular 5 正式版都快出了, 不过主要是性能升级. 我认为angular 4还是很适合企业的, 就像.net一样. 我用的是windows 10 安装工具: git for ...
- 使用angular4和asp.net core 2 web api做个练习项目(二), 这部分都是angular
上一篇: http://www.cnblogs.com/cgzl/p/7755801.html 完成client.service.ts: import { Injectable } from '@an ...
- 使用angular4和asp.net core 2 web api做个练习项目(四)
第一部分: http://www.cnblogs.com/cgzl/p/7755801.html 第二部分: http://www.cnblogs.com/cgzl/p/7763397.html 第三 ...
- 基于ASP.NET Core 创建 Web API
使用 Visual Studio 创建项目. 文件->新建->项目,选择创建 ASP.NET Core Web 应用程序. 基于 ASP.NET Core 2.0 ,选择API,身份验证选 ...
- ASP.NET Core Restful Web API 相关资源索引
GraphQL 使用ASP.NET Core开发GraphQL服务器 -- 预备知识(上) 使用ASP.NET Core开发GraphQL服务器 -- 预备知识(下) [视频] 使用ASP.NET C ...
- 使用 ASP.NET Core 创建 Web API及链接sqlserver数据库
创建 Web API https://docs.microsoft.com/zh-cn/aspnet/core/tutorials/first-web-api?view=aspnetcore-3.0& ...
随机推荐
- NOI2019 酱油记
今天是 \(7.18\) ,考完二试炸的很惨-于是我就来写游记了. DAY 0 签到日(7.14) 还没起床,原先定的飞机就被取消了,只好改签. 然而还是很早到的机场,等了好久好久. 到广州咯~下大雨 ...
- [洛谷P3254] [网络流24题] 圆桌游戏
Description 假设有来自m 个不同单位的代表参加一次国际会议.每个单位的代表数分别为ri (i =1,2,--,m). 会议餐厅共有n 张餐桌,每张餐桌可容纳ci (i =1,2,--,n) ...
- 【JQ】 validate验证表单时多个name相同的元素的解决办法
使用jQuery.validate插件http://jqueryvalidation.org/,当节点的name相同时候,脚本特意忽略剩余节点,导致所有相关节点的errMsg都显示在第一个相关节点上. ...
- manually Invoking Model Binding / Model Binding /Pro asp.net mvc 5
限制绑定器 数据源
- 超越队西柚考勤系统——beta冲刺3
一.成员列表 姓名 学号 蔡玉蓝(组长) 201731024205 郑雪 201731024207 何玉姣 201731024209 王春兰 201731024211 二.SCRUM部分 (1)各成员 ...
- [ZJOI2008]树的统计(树链剖分)
[ZJOI2008]树的统计(luogu) Description 一棵树上有 n 个节点,编号分别为 1 到 n,每个节点都有一个权值 w.我们将以下面的形式来要求你对这棵树完成一些操作: I. C ...
- Django中model的class Meta
Class Meta 作用:使用内部类来提供一些metadata,以下列举一些常用的meta:1,abstract:如下段代码所示,将abstract设置为True后,CommonInfo无法作为一个 ...
- composer实践总结
composer composer 概述 FIG 最初由几位知名 PHP 框架开发者发起,在吸纳了许多优秀的大脑和强健的体魄后,提出了 PSR-0 到 PSR-4 五套 PHP 非官方规范: PSR- ...
- CSRF攻击原理
CSRF CSRF(Cross-site request forgery)跨站请求伪造,CSRF是一种夹持用户在已经登陆的web应用程序上执行非本意的操作的攻击方式.相比于XSS,CSRF是利用了系统 ...
- JDBC——CreateStatement和PrepareStatement作用区别
本文主要讲了PrepareStatement和CreateStatement的作用区别,大家可以一起学习!走后端的小伙伴都会必修JDBC,在前段时间作者实训期间,看到老师举例的时候用了CreateSt ...