Wednesday, March 1, 2017

Resolved: Enable CORS on OWIN the right way

I was having difficulty, probably like you, trying to figure out how to get CORS working on a OWIN self-hosted application.  There were so many answers posted, but seemed like so many of them were based on older versions of Visual Studio / .NET.

Here is what I finally found to work for me; hopefully this will help you as well.  This is as of Visual Studio 2015 in early March 2017.

  1. Add nuget packages to the web api project:
    1. Microsoft.AspNet.WebApi.Cors
    2. Microsoft.Owin.Cors (this will also install Microsoft.AspNet.Cors)
  2. Modify startup.cs, Configuration(IAppBuilder app), add this line:

    app.UseCors(CorsOptions.AllowAll);

    and add it before the line:

    app.UseWebApi(config);
  3. Add the following attribute on my web api controller class:

    [EnableCors("*", "*", "*")]
These three steps got things finally working.

No comments:

Can't RDP? How to enable / disable virtual machine firewall for Azure VM

Oh no!  I accidentally blocked the RDP port on an Azure virtual machine which resulted in not being able to log into the VM anymore.  I did ...