ASP.NET Core 利用中间件支持跨域请求
方法1:
在Startup的ConfigureServices()中添加services.AddCors()
在Startup的Configure()中添加app.UseCors(); 保证其在app.UseMvc();之前
app.UseCors(builder => builder .AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials()); app.UseMvc();
原文链接
https://stackoverflow.com/questions/44379560/how-to-enable-cors-in-asp-net-core-webapi
方法2:
1、public void Configure(IApplicationBuilder app, IHostingEnvironment env)方法里面
不要加上:app.UseCors();
2、上面方法加上:
app.UseMiddleware<CorsMiddleware>();
3、中间代码如下:
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); } }