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.Response.Headers.Add("Access-Control-Allow-Credentials", "true"); httpContext.Response.Headers.Add("Access-Control-Max-Age", "86400");//缓存一天 httpContext.Response.StatusCode = 204; return httpContext.Response.WriteAsync("OK"); } 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.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>(); } } }
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseCorsMiddleware();
}
本文介绍了一个自定义的CORS(跨源资源共享)中间件实现,该中间件用于ASP.NET Core应用程序中,确保了不同域之间的资源可以被安全地访问。通过在HTTP请求管道中添加此中间件,开发者可以轻松地配置跨域请求策略。

被折叠的 条评论
为什么被折叠?



