owin cors or web api cors

前端 未结 2 1114

there are 100s of question on CORS on web-api, and on how to enable CORS, there is a different answer each one provides. I am so confused and dont know which answer is corre

2条回答
  •  孤城傲影
    2020-12-15 05:34

    There is a way to fix this. Since OWIN and ASP.NET.CORS libraries are working simultaneously. Owin token or authentication method needs to be configured to enable CORS separately from all other API controllers.

    Fist thing first, don't use cors with Owin in Startup.cs :

    public void Configuration(IAppBuilder app)
    {
        //app.UseCors(CorsOptions.AllowAll);
    

    Find GrantResourceOwnerCredentials method and add Access-Control-Allow-Origin to context so when it returns a call after authentication is completed that browser finds the header and accepts it.

    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "http://localhost" });
    

    Now install Microsoft.AspNet.WebApi.Cors package from Nuget to your webapi project, and add this to Register method

    public static void Register(HttpConfiguration config)
    {
            var cors = new EnableCorsAttribute("http://localhost, ", "accept,accesstoken,authorization,cache-control,pragma,content-type,origin", "GET,PUT,POST,DELETE,TRACE,HEAD,OPTIONS");
    
            config.EnableCors(cors);
    

    Worked for me.

提交回复
热议问题