Raas Masood
Raas Masood

Reputation: 1565

web api routes not working with CORS enabled.

I have CORS enabled in my web api application. and i have API controllers with both classic REST Function names like Get() and Get(string id) and a controllers with custom function names e.g. [HttpGet] GetSomeThing()

i have routes configured like this

config.EnableCors();
config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

                config.Routes.MapHttpRoute(
        name: "ApiById",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
        );

with this arrangement i get an error No 'Access-Control-Allow-Origin' header is present when i try to call controller with Classic REST functions.

e.g. /api/Controller

and if i take route with action after route without action , it gives me the same error on controller calls with custom function names.

e.g. /api/Controller/Function

please note that i have

    [EnableCorsAttribute("http://localhost:xxxx", "*", "*")]

attribute on both controllers. and these calls are being made from angular application.

kindly advice.

Upvotes: 2

Views: 2273

Answers (2)

kingkeamo
kingkeamo

Reputation: 366

I ran into this issue and I found it a nightmare to get cors to work.

The fix for me in the end was to remove all references to cors in my app and add just one line in the WebAPIConfig

 public static void Register(HttpConfiguration config)
    {
        config.EnableCors(new EnableCorsAttribute("*", "*", "GET, POST, OPTIONS, PUT, DELETE, TOKEN"));

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "ActionApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "rest/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
        jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

        var json = config.Formatters.JsonFormatter;
        json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
        config.Formatters.Remove(config.Formatters.XmlFormatter);

    }

I also removed the custom headers from my web.config. Hope this help anyone else facing cors issues.

Upvotes: 0

Victor Grippi
Victor Grippi

Reputation: 81

Had the same issue. Fixed it by adding CORS headers directly to web.config. No other changes are needed.

  <system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Methods" value="GET, POST, OPTIONS" />
        <add name="Access-Control-Allow-Headers" value="content-type, accept, SOAPAction, origin" />
      </customHeaders>
    </httpProtocol>
  </system.webServer>

Additionally, if you installed CORS via NuGet and were using a previous version of WebAPI, then you may need to uninstall it. CORS will update certain core WebAPI assemblies that may cause compatibility issues, i.e., routes not working.

And of course, you will probably want to limit the allowed origins by replacing the "*" in the Access-Control-Allow-Origin value with the URL's you want to allow.

Upvotes: 1

Related Questions