.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. context:component-scan标签的诠释

    XML中配置context:component-scan时,spring会自动的扫描这个包下被这些注解标识的类@Component,@Service,@Controller,@Repository,同 ...

  2. Oracle GoldenGate 19.1新特性

    1.GoldenGate 19.1 新特性概览a.支持Oracle数据库19.1 长期支持发布版本.集成Oracle GoldenGate 12.3版的最终补丁集更新.b.微服务的安全性和可管理性增强 ...

  3. shell 条件测试

    1.文件相关 -e 判断文件或者文件夹是否存在 -d 判断目录是否存在 -f 判断文件是否存在 -r 判断是否有读权限 -w 判断是否有写权限 -x 判断是否有执行权限 1.1命令行使用 [root@ ...

  4. QTP测试web时:打开ie浏览器进行录制但qtp录制脚本为空

    1. 关闭ie的保护模式:设置——internet选项——安全——取消勾选“启用保护模式” 这一步很关键,之前试过很多步骤,只有这个成功了. 修改后如果可行即可.如果不行再进行下面操作: 2.关闭杀毒 ...

  5. 对于传统scnece-classfication的分析

    BoW模型最初应用于文本处理领域,用来对文档进行分类和识别.BoW 模型因为其简单有效的优点而得到了广泛的应用.其基本原理可以用以下例子来给予描述.给定两句简单的文档: 文档 1:“我喜欢跳舞,小明也 ...

  6. 自定义BeanDefinitionRegistryPostProcessor注册bean

    自定义BeanDefinitionRegistryPostProcessor 概述 BeanDefinitionRegistryPostProcessor继承自BeanFactoryPostProce ...

  7. 养成编程思维,可以从python开始,今天说说python注释

    先看思维导图!对内容简单了解一下. 提高代码的可读性,需要提供对代码的注释.python注释,主要作用在代码中,对代码功能进行解释,是一种标注性文字.一般情况下分成三类,单行注释.多行注释.中文声明注 ...

  8. docker相关----解决tomcat容器启动成功,无法访问的问题

    使用docker安装了tomcat镜像,默认为latest最新的(8.5.50版本),依据tomcat镜像创建容器并同时做了端口映射 命令为:docker run --name tomcat01 -d ...

  9. selenium窗口截图操作

    selenium窗口截图操作 使用背景:在自动化测试过程中,可能遇到执行错误情况,那么怎么样及时捕获出错信息/界面? 可以使用  get_screenshot_as_file(self,filenam ...

  10. The current test process

    样机测试 测试前: 工作内容: 1.需求分析.编写.评审: 项目开工会由项目负责人参加,参加会议时做好笔记,对项目的功能类似,功能模块,测试时间点有个大致的了解. 原始需求进行需求文档细化:按照模块进 ...