c# Web Api with CORS Enabled and the dreaded No &#

2019-02-23 11:55发布

问题:

I have a C# Web API project. I created a Controller using the Web API 2 standard. I am trying to enable CORS on only one action, this is what I have:

namespace MyProject.Controllers
{
    public class MyControllerController : ApiController
    {
        // POST api/mycontroller
        [EnableCors("http://link.myurl.com", "*", "*")]
        public bool Post(MyCustomObject customObject)
        {
            // Function that returns Bool
            return myFunction(customObject);
        }
    }
}

My WebApiConfig.cs looks like this:

// Web API configuration and services
config.EnableCors(); 

// Web API routes
config.MapHttpAttributeRoutes();

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

// Ignore Null values on JSON Returns
config.Formatters.JsonFormatter.SerializerSettings = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore };
config.Formatters.JsonFormatter.SerializerSettings = new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore };

Here is the Cross-Domain AJAX call:

$.ajax({
    type: "POST",
    url: 'http://myurl.com/api/mycontroller',
    data: JSON.stringify({ Type: 'TextHere', OtherInfo: 'TextHere' }),
    contentType: "application/json",
    success: function (data) {
    }
});

Based off tutorials such as this one: http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api#how-it-works, I should have everything properly setup.

I continue to get the following error in Chrome:

XMLHttpRequest cannot load http://myurl.com/api/mycontroller. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://link.myurl.com' is therefore not allowed access.

When I take a look at the calls using Fiddler, I notice that the Pre-flight Origin check goes through fine with Status 200, but when the actual call is made it returns 500.

Interestingly enough, the transactions are committed to the database even though the call failed. It's almost like the Pre-flight Origin check is running through the code when it should just be checking for Allow Origin.

I've tried adding the following to web.config:

<system.webServer>
   <httpProtocol>
     <customHeaders>
       <add name="Access-Control-Allow-Origin" value="http://link.myurl.com" />
     </customHeaders>
   </httpProtocol>
 <system.webServer>

If I leave the [EnableCors] line, then I get an error that two values are specified (http://link.myurl.com) when there can only be one. If I remove the [EnabledCors] line, I get the original error.

If you can't already tell, I'm at a loss here. Ironically it is working (database actions being committed), but the browser thinks its not working and never accepts the JSON return data.

HELP?

回答1:

I'm not sure why this worked this time around, but I got it working. The main difference might be the library I installed using NuGet:

Microsoft ASP.NET Web API 2.2 Cross-Origin Support

I then set the WebApiConfig.cs file as specified in my initial post, as well as the EnableCors option above the Action I wanted to allow it on.

I did NOT set anything in the web.config file.

I no longer receive the error, must have something to do with the NuGet package.



回答2:

I got caught out by this. You have to EnableCORS after the routes attribute have been mapped if using Attribute routing.

// Web API routes
config.MapHttpAttributeRoutes();

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

// Web API configuration and services
config.EnableCors();