CORS support for web API in VisualStudio 2012

So I have 2 web services – one is a web-api service and the other is some Frankenstein.  When a CORS request comes over to the server it comes with the “OPTIONS” HTTP method, so I’m guessing there is an “options” attribute you can add to customize the request for a specific method…  Not sure why you would do that though.

Here are the notes I’ve collected from the process of adding support to both services:

ScottGu: http://weblogs.asp.net/scottgu/archive/2013/04/19/asp-net-web-api-cors-support-and-attribute-based-routing-improvements.aspx

http://aspnetwebstack.codeplex.com/wikipage?title=CORS%20support%20for%20ASP.NET%20Web%20API&referringTitle=Specs

Web API steps
My big hangup is doing this in visual studio 2012 – it doesn’t appear to be made to work out of the box in vs2012…
– Include System.Web.Cors.dll and System.Web.Http.Cors.dll – had to download the nuget package Microsoft.AspNet.WebApi.Cors.
– Enable CORS in the WebApiConfig.Register – you can then use the [EnableCors] attribute.  However the example in the codeplex example appears to be bad —  You can’t instantiate a EnableCorsAttribute object without parameters…
– To load settings from your config, you have to implement an ICorsPolicyProvider class
– Examples in the second link show how to implement it as a custom attribute
– Had to add a dependent section to the web.config:

      <dependentAssembly>
        <assemblyIdentity name="System.Web.Http" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
      </dependentAssembly>

–  Had to follow the nuget update steps in: http://stackoverflow.com/questions/18347290/webapi-odata-5-0-beta-accessing-globalconfiguration-throws-security-error

– Added one more dependent section to the web.config

      <dependentAssembly>
        <assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
      </dependentAssembly>
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s