.NETCore3.1允许跨域
1.新建跨域类【CorsMiddleware】
/// <summary> /// 跨域帮助类 /// </summary> public class CorsMiddleware { private readonly RequestDelegate next; public CorsMiddleware(RequestDelegate next) { this.next = next; } public async Task Invoke(HttpContext context) { if (context.Request.Headers.ContainsKey(CorsConstants.Origin)) { context.Response.Headers.Add("Access-Control-Allow-Origin", context.Request.Headers["Origin"]); context.Response.Headers.Add("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS,HEAD,PATCH"); context.Response.Headers.Add("Access-Control-Allow-Headers", context.Request.Headers["Access-Control-Request-Headers"]); context.Response.Headers.Add("Access-Control-Allow-Credentials", "true"); if (context.Request.Method.Equals("OPTIONS")) { context.Response.StatusCode = StatusCodes.Status200OK; return; } } await next(context); } }
2.在Startup.cs的【Configure】里引用,注意要放到【app.UseMvc()】之后
//跨域 app.UseMiddleware<CorsMiddleware>();
3.还有几种以供参考(我这边是部署到CentOS7上,发现错误就换掉了,后面发现是端口被占用了)
感谢:https://www.cnblogs.com/linyijia/p/12981830.html