.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& ...
随机推荐
- noip2018 考前提醒!
适应Noilinux 1.终端操作 打开终端 \(Ctrl+Alt+T\) 打开文件夹 \(cd\) +名称 新建文件夹 \(mkdir\) +名称 打开 \(vim\) 配置 \(vim ~/.vi ...
- C语言进阶——全局变量
全局变量 ·定义在函数外面的变量是全局变量 ·全局变量具有全局的生存期和作用域 ·它们与任何函数都无关 ·在任何函数内部都可以使用它们 全局变量初始化 ·没有做初始化的全局变量会得到0值 ·指针会得到 ...
- latex之在windows环境下能够在latex中使用中文
今天要把前段时间的实验用英语先记录下来,自己就想根据原来会议的模版弄一个简易的页面(英语),突然想到之前用英文模板时是不能输入中文的,于是想着怎么在latex中输入中文,折腾了许久,终于成功了,现在分 ...
- .NET Core Install for Ubuntu 14.04
Add the dotnet apt-get feed In order to install .NET Core on Ubuntu or Linux Mint, you need to fir ...
- Math.Atan2 方法
返回正切值为两个指定数字的商的角度. public static double Atan2 ( double y, double x ) 参数 y 点的 y 坐标. x 点的 x 坐标. 返回值 角 ...
- Java的String类常用方法
一.构造函数 String(byte[ ] bytes):通过byte数组构造字符串对象. String(char[ ] value):通过char数组构造字符串对象. String(Sting or ...
- 1.Vue初始及相关Vue核心组件
1.Vue官方文档 官网文档:https://cn.vuejs.org/v2/guide/ 2.Vue-cli官方文档(脚手架) 官网文档:https://cli.vuejs.org/zh/guide ...
- 工具之cut
转自http://www.cnblogs.com/dong008259/archive/2011/12/09/2282679.html cut:正如其名就是“剪”,和sed一样,一行为单位,对数据进行 ...
- Linux 6种日志查看方法,不会看日志会被鄙视的
作为一名后端程序员,和Linux打交道的地方很多,不会看Linux日志,非常容易受到来自同事和面试官的嘲讽,所以掌握一种或者几种查看日志的方法非常重要. Linux查看日志的命令有多种: tail.c ...
- Linux 常用工具openssh之ssh-add
前言 ssh-add命令是把专用密钥添加到ssh-agent的高速缓存中,从而提高ssh的认证速度 语法 ssh-add [-cDdLlXx] [-t life] [file ...] 选项 -D:删 ...