.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& ...
随机推荐
- [LOJ#3022][网络流]「CQOI2017」老 C 的方块
题目传送门 定义有特殊边相邻的格子颜色为黑,否则为白 可以看出,题目给出的限制条件的本质是如果两个小方块所在的格子 \(x\) 和 \(y\) 为两个相邻的黑格,那么 \(x\) 和 \(y\) 之间 ...
- Knative 简介
原文地址:https://yq.aliyun.com/articles/658800
- MySQL5.6数据导入MySQL5.7报错:ERROR 1031 (HY000)
一.故障现象 今天将一个在MySQL5.7上的数据导入到MySQL5.6里面去,默认存储引擎都是InnoDB,导入报错如下: [root@oratest52 data]# mysql -uroot - ...
- 微信小程序如何创建云函数并安装wx-server-sdk依赖
时间:2020/01/23 步骤 1.在微信开发者工具中云函数所在的文件夹的图标与其他文件夹是不同的,如下(第一个是云函数): 如果需要使一个普通文件变为云函数文件夹,需要在project.confi ...
- jQuery使用ajax向node后台发送对象、数组参数
引言 最近在使用jq,做一些小demo,但是突然发现jq使用ajax像后台(node)传递一个对象参数,但是后台却接收不了. 原因 后面了解到.jq会将一个对象解析成obj[key]: value这样 ...
- 一个支持高网络吞吐量、基于机器性能评分的TCP负载均衡器gobalan
一个支持高网络吞吐量.基于机器性能评分的TCP负载均衡器gobalan 作者最近用golang实现了一个TCP负载均衡器,灵感来自grpc.几个主要的特性就是: 支持高网络吞吐量 实现了基于机器性能评 ...
- python中的变量和字符串
一.变量 1.python变量 *变量用于存储某个或某些特定的值,它与一个特定标识符相关联,该标识符称为变量名称.变量名指向存储在内存中的值.在创建变量时会在内存中开辟一个空间.基于变量的数据类型,解 ...
- python dict 中的中文处理
dict1 = {'中':'国 '} print dict1 ##{'\xc3\xa4\xc2\xb8\xc2\xad': '\xc3\xa5\xc2\x9b\xc2\xbd'} import jso ...
- POJ_1185_状态压缩dp
http://poj.org/problem?id=1185 一次考虑两行,比一行略为复杂.sta保存每种状态炮兵位置,sum保存每种状态当行炮兵总数,a保存地形,dp[i][j][k]表示到第i行当 ...
- js变量和函数提升
写在前面: 变量提升是 声明提升,初始化不会提升,比如说 var a=1; console.log(a); 实际是这样执行(个人理解,仅供参考) var a; console.log(a); a=1; ...