.Net Core 跨域
Startup.cs
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseCorsMiddleware();
//其它代码...... }
CorsMiddleware.cs
using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; namespace VipSoft.Web { public class CorsMiddleware { private readonly RequestDelegate _next; public CorsMiddleware(RequestDelegate next) { _next = next; } public Task Invoke(HttpContext httpContext) { if (httpContext.Request.Method == "OPTIONS") { httpContext.Response.Headers.Add("Access-Control-Allow-Origin", httpContext.Request.Headers["Origin"]); httpContext.Response.Headers.Add("Access-Control-Allow-Headers", httpContext.Request.Headers["Access-Control-Request-Headers"]); httpContext.Response.Headers.Add("Access-Control-Allow-Methods", httpContext.Request.Headers["Access-Control-Request-Method"]); httpContext.Response.Headers.Add("Access-Control-Allow-Credentials", "true"); httpContext.Response.Headers.Add("Access-Control-Max-Age", "86400");//缓存一天 httpContext.Response.StatusCode = 204; #【用 AspNetCoreRateLimit 的时候,这行代码要去掉,否则会报:StatusCode cannot be set because the response has already started.】 return httpContext.Response.WriteAsync(""); } if (httpContext.Request.Headers["Origin"] != "") { httpContext.Response.Headers.Add("Access-Control-Allow-Origin", httpContext.Request.Headers["Origin"]); } httpContext.Response.Headers.Add("Access-Control-Allow-Headers", httpContext.Request.Headers["Access-Control-Request-Headers"]); httpContext.Response.Headers.Add("Access-Control-Allow-Methods", httpContext.Request.Headers["Access-Control-Request-Method"]); httpContext.Response.Headers.Add("Access-Control-Allow-Credentials", "true"); httpContext.Response.Headers.Add("Access-Control-Max-Age", "86400");//缓存一天 return _next.Invoke(httpContext); } } // Extension method used to add the middleware to the HTTP request pipeline. public static class CorsMiddlewareExtensions { public static IApplicationBuilder UseCorsMiddleware(this IApplicationBuilder builder) { return builder.UseMiddleware<CorsMiddleware>(); } } }
本文来自博客园,作者:VipSoft 转载请注明原文链接:https://www.cnblogs.com/vipsoft/p/12878559.html