.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调整配置代码位置后,得知:

  1. AllowAnyOrigin 方法,在新的 CORS 中间件已经被阻止使用允许任意 Origin,所以该方法无效。
  2. AllowCredentials 方法,自从 .NET Core 2.2 之后,不允许和AllowAnyOrigin同时调用。
  3. WithOrigins 方法,在 .NET Core 3.1 中有bug,具体原因未知,暂时只能用SetIsOriginAllowed(t=> true)代替,等效.AllowAnyOrigin方法。
  4. 创建项目默认的模板中,app.UseHttpsRedirection()在前面,所以我将app.UseCors()放在它后面,这是导致HTTP 307 Temporary Redirect福报的根本原因之一。
  5. 度娘告诉我,app.UseCors()方法要在app.UseAuthentication()之后,是误人子弟的,其实放在它前面也可以,并且app.UseCors()要在app.UseRouting()之后,app.UseEndpoints()app.UseHttpsRedirection()之前
  6. 使用fetch跨域请求时,要注意controller的action是否有设置除了HttpOptions之外的其它Http Method方法,如果有要加上HttpOptions标记特性,因为fetch跨域请求会先执行OPTIONS预请求。
  7. 使用fetch请求需要JWT认证的接口时,除了在HTTP Headers设置Authorization之外,还需要设置'credentials': 'include'
  8. app.UseXxxxxx方法,引入中间件时,要注意管道(Middleware)注册顺序。

参考:

源代码

以下是在 .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的更多相关文章

  1. angular4和asp.net core 2 web api

    angular4和asp.net core 2 web api 这是一篇学习笔记. angular 5 正式版都快出了, 不过主要是性能升级. 我认为angular 4还是很适合企业的, 就像.net ...

  2. .net core 3 web api jwt 一直 401

    最近在给客户开发 Azure DevOps Exension, 该扩展中某个功能需要调用使用 .NET Core 3 写的 Web Api. 在拜读了 Authenticating requests ...

  3. 温故知新,使用ASP.NET Core创建Web API,永远第一次

    ASP.NET Core简介 ASP.NET Core是一个跨平台的高性能开源框架,用于生成启用云且连接Internet的新式应用. 使用ASP.NET Core,您可以: 生成Web应用和服务.物联 ...

  4. 使用angular4和asp.net core 2 web api做个练习项目(一)

    这是一篇学习笔记. angular 5 正式版都快出了, 不过主要是性能升级. 我认为angular 4还是很适合企业的, 就像.net一样. 我用的是windows 10 安装工具: git for ...

  5. 使用angular4和asp.net core 2 web api做个练习项目(二), 这部分都是angular

    上一篇: http://www.cnblogs.com/cgzl/p/7755801.html 完成client.service.ts: import { Injectable } from '@an ...

  6. 使用angular4和asp.net core 2 web api做个练习项目(四)

    第一部分: http://www.cnblogs.com/cgzl/p/7755801.html 第二部分: http://www.cnblogs.com/cgzl/p/7763397.html 第三 ...

  7. 基于ASP.NET Core 创建 Web API

    使用 Visual Studio 创建项目. 文件->新建->项目,选择创建 ASP.NET Core Web 应用程序. 基于 ASP.NET Core 2.0 ,选择API,身份验证选 ...

  8. ASP.NET Core Restful Web API 相关资源索引

    GraphQL 使用ASP.NET Core开发GraphQL服务器 -- 预备知识(上) 使用ASP.NET Core开发GraphQL服务器 -- 预备知识(下) [视频] 使用ASP.NET C ...

  9. 使用 ASP.NET Core 创建 Web API及链接sqlserver数据库

    创建 Web API https://docs.microsoft.com/zh-cn/aspnet/core/tutorials/first-web-api?view=aspnetcore-3.0& ...

随机推荐

  1. 使用 LinkedBlockingQueue 实现简易版线程池

    前一阵子在做联系人的导入功能,使用POI组件解析Excel文件后获取到联系人列表,校验之后批量导入.单从技术层面来说,导入操作通常情况下是一个比较耗时的操作,而且如果联系人达到几万.几十万级别,必须拆 ...

  2. .net core 第三方工具包集合

    日志 Nlog 单点登录

  3. 从零开始ming的多人联机游戏(3)为socket通讯添加mysql数据库

    macOS下visual studio C#加载mySql 本文在上一节的基础上,添加了mysql数据库的功能.client发送信息给服务器后,服务器将收到的消息保存在数据库中. 如果client发送 ...

  4. NOI2.4 2011

    描述 已知长度最大为200位的正整数n,请求出2011^n的后四位. 输入 第一行为一个正整数k,代表有k组数据,k<=200接下来的k行, 每行都有一个正整数n,n的位数<=200 输出 ...

  5. sqli_labs学习笔记(一)Less-21~Less-37

    续上,开门见山 Less-21 Cookie Injection- Error Based- complex - string ( 基于错误的复杂的字符型Cookie注入) 登录后页面 圈出来的地方显 ...

  6. C#反射与特性(九):全网最全-解析反射

    目录 1,判断类型 1.1 类和委托 1.2 值类型 1.3 接口 1.4 数组 2, 类型成员 2.1 类 2.2 委托 2.3 接口 [微信平台,此文仅授权<NCC 开源社区>订阅号发 ...

  7. Nginx-负载均衡实现解读

    负载均衡在服务端开发中算是一个比较重要的特性.因为Nginx除了作为常规的Web服务器外,还会被大规模的用于反向代理前端,因为Nginx的异步框架可以处理很大的并发请求,把这些并发请求hold住之后就 ...

  8. docker扫盲,面试连这都不会就等着挂吧!

    现在很多公司项目部署都是采用K8S docker容器方式,出门面试被问的概率极大,如果被面试官问docker相关知识点直接懵逼,那么基本就是被pass了,除非其他方面技术过硬.所以这种相对前沿的技术, ...

  9. xhsell关闭jupyter仍然运行的命令

    nohup jupyter notebook & nohup 和 &都是linux的命令 1.& 当在前台运行某个作业时,终端被该作业占据:可以在命令后面加上& 实现后 ...

  10. Activity--Eclipse安装Activity designer插件失败

    案例 今天使用Eclipse 安装Activity designer插件时,出现了如下错误: An error occurred while collecting items to be instal ...