Enable OPTIONS header for CORS on .NET Core Web API

后端 未结 7 1579
温柔的废话
温柔的废话 2020-11-28 06:55

I solved this problem after not finding the solution on Stackoverflow, so I am sharing my problem here and the solution in an answer.

After enabling a cross domain p

7条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-28 07:44

    Add a middleware class to your project to handle the OPTIONS verb.

    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Http;
    using Microsoft.AspNetCore.Hosting;
    
    namespace Web.Middlewares
    {
        public class OptionsMiddleware
        {
            private readonly RequestDelegate _next;
    
            public OptionsMiddleware(RequestDelegate next)
            {
                _next = next;
            }
    
            public Task Invoke(HttpContext context)
            {
                return BeginInvoke(context);
            }
    
            private Task BeginInvoke(HttpContext context)
            {
                if (context.Request.Method == "OPTIONS")
                {
                    context.Response.Headers.Add("Access-Control-Allow-Origin", new[] { (string)context.Request.Headers["Origin"] });
                    context.Response.Headers.Add("Access-Control-Allow-Headers", new[] { "Origin, X-Requested-With, Content-Type, Accept" });
                    context.Response.Headers.Add("Access-Control-Allow-Methods", new[] { "GET, POST, PUT, DELETE, OPTIONS" });
                    context.Response.Headers.Add("Access-Control-Allow-Credentials", new[] { "true" });
                    context.Response.StatusCode = 200;
                    return context.Response.WriteAsync("OK");
                }
    
                return _next.Invoke(context);
            }
        }
    
        public static class OptionsMiddlewareExtensions
        {
            public static IApplicationBuilder UseOptions(this IApplicationBuilder builder)
            {
                return builder.UseMiddleware();
            }
        }
    }
    

    Then add app.UseOptions(); this as the first line in Startup.cs in the Configure method.

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        app.UseOptions();
    }
    

提交回复
热议问题