using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace DDYWEBAPI.Middleware { 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", "");//缓存一天 httpContext.Response.StatusCode = ; return Task.CompletedTask; } 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", "");//缓存一天 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>(); } } }
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseCorsMiddleware(); }
版权声明:除特别声明外,本站所有文章皆是本站原创,转载请以超链接形式注明出处!