Web Api Still Getting Cors Errors After Installing Microsoft.AspNet.Cors And Enabling Cors On Controller

37349445 11 Reputation points

I am buildind a Web Api app locally and I am calling the methods using simple jQuery ajax method calls. As per the title I have installed the Microsoft.AspNet.Cors package via nuget and enabled cors in my WebApiConfig.cs and on my controller like this

[EnableCors(origins: "https://localhost:44397", headers: "", methods: "", exposedHeaders: "X-My-Header")]

I have even tried this

[EnableCors(origins: "", headers: "", methods: "", exposedHeaders: "")]

but when I make the call via ajax I still get the error - Access to XMLHttpRequest at 'https://localhost:44397/api/Default/PostRegisterUser' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Why is this happening and how do I resolve this?

ASP.NET: A set of technologies in the .NET Framework for building web applications and XML web services.API: A software intermediary that allows two applications to interact with each other.
312 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Don Slattery 1 Reputation point

    Strangely I was dealing with a very similar issue and found an answer to my situation. In your case you have no origin. In my case I did have an origin but CORS was not working as I expected. Once you get your origin sorted out, you'll probably still have a similar issue to mine where CORS still won't work even though you configured it. The solution I came across was to update the web.config:
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Headers" value="Content-Type" />
    <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />

    This worked for me.

    0 comments No comments