在.Net Core3.1下WebApi跨域的处理比在.Net Core2.1时复杂的多了
1.在Startup类种的ConfigureServices方法中增加
services.AddCors(
options => options.AddPolicy("AllowCors",
p => p.WithOrigins("http://*.*.*.*","http://localhost:8080")
//p.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod()
//.AllowCredentials()//.net 2.1下可以使用
)
注意AllowCredentials()此方法在.net core2.1下可以使用在.net core3.1下就不行了。
2.在Configure方法中
//配置Cors 放在UseRouting和UseEndpoints之间
app.UseCors("AllowCors");
注意此方法要放在app.UseRouting()和app.UseEndpoints()之间
3.自定义中间件
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace MyMis.MvcExtend.MiddleWare {
public class CorsMiddleware {
private readonly RequestDelegate _next;
public CorsMiddleware(RequestDelegate next) {
_next = next;
}
public async Task Invoke(HttpContext context) {
//if (!context.Response.Headers.ContainsKey("Access-Control-Allow-Origin")) {
//context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
//}
if (!context.Response.Headers.ContainsKey("Access-Control-Allow-Credentials")) {
context.Response.Headers.Add("Access-Control-Allow-Credentials", "true");
}
await _next(context);
}
}
}
using Microsoft.AspNetCore.Builder;
using System;
using System.Collections.Generic;
using System.Text;
namespace MyMis.MvcExtend.MiddleWare {
public static class CorsMiddlewareExtension {
/// <summary>
/// 跨域配置中间件
/// </summary>
/// <param name="app"></param>
/// <returns></returns>
public static IApplicationBuilder UseCorsAllowOrigin(this IApplicationBuilder app) {
return app.UseMiddleware<CorsMiddleware>();
}
}
}
然后在Startup类种的Configure方法的开头中注册
app.UseCorsAllowOrigin();//配置Cors
使用Vue前段调用后端.net core3.1开发的一直会提示Access-Control-Allow-Credentials这个有错误,在.net core2.1的时候注册时可以使用AllowCredentials()但是现在不行了,后来就在定义的中间件上请求头上加上这个这样就可以了