CORS is not working in web api with OWIN authentication

前端 未结 5 602
花落未央
花落未央 2020-12-05 00:36

In my application i am using web api with token based authentication with CORS support, but when client request for the token, an error occured due to CORS (Cross-Origin Re

5条回答
  •  粉色の甜心
    2020-12-05 01:24

    I had this similar problem, I tried all the options above in startup.cs i added app.UseCors(CorsOptions.AllowAll); at the top and in the WebApiConfig i disabled

    public static void Register(HttpConfiguration config)
    {
        //var cors = new EnableCorsAttribute("*", "*", "*");
        //config.EnableCors(cors);
    }
    

    and also disabled cors in

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

    And repeated this in reverse order and also included entries in web.config but all did not work.

    When I begun asking myself why is app.UseWebApi(config); not accessible yet I have seen it work somewhere. I looked around and found out installing Install-Package Microsoft.AspNet.WebApi.OwinSelfHost fixes it.

    Eventually, it fixed the whole problem, though app.UseCors(CorsOptions.AllowAll) has to be placed first in the startup.cs method. In fact without app.UseWebApi(config), I tested in postman and the end points actually didn't exist. Overall it's working pretty well for me now.

提交回复
热议问题