How to enable cors on your local .net project in 3 steps

If you are interested in setting up CORS on an external server (specifically Azure cloud) then check my post here.  Before you do that, though, you may want to continue reading this post to see how to test your web API calls locally with CORS enabled.

The What?

If you try to build a .net webAPI service and deploy it locally (F5) then try to invoke from a web client running on something other than the same domain (like from another port) you will get a CORS error.  I’m going to assume that if you’re here you already know what CORS is (More about CORS here).  The following is a silver bullet for this issue (pun intended).

Why would you want to do this?

No longer are API’s just for social media giants trying to figure out how to make a profit.  Nor are they just for nimble startups.   This trend is also now increasing rapidly with enterprise project deliveries due to the ubiquity of using APIs as integral architecture elements.  The benefits are numerous including adding “stickiness” between your customers and your brand (that’s the REAL reason they are called webhooks) and enabling you to scale rapidly (think micro-services and Docker containers).
This latter consideration makes you, as a technology company, more readily vendable/consumable; not just to other developers, but to potential buyers of your whole company (for instance, that large retail company you have been angling to in your exit strategy).  Hence API development makes your company more valuable.   All these reasons and more are why your boss has you building a CORS service.  I digress.

The net net is that if you are building web apps these days you are likely consuming external web services and now you are authoring external web services so you will need to know this trick for enabling CORS in your local webAPI projects.

How?

So you’ve built that web API service from Visual Studio 2017 and it’s running smootly locally on your local box.  Ahhhh the power of localhost.  Now you deftly slip into Visual Studio Code and fire up that wicked Angular (not js.. Just Angular.  Sublime.  And yet… so stupid) app you’ve been working on.  You click a few times (you’re not the best UX designer) and then enter some data then click again and “boom”:

CORS Error in Chrome dev tools

CORS Error in Chrome dev tools

Execute the following 3 steps to get around this and back to the awesomeness you were previously set to impart on the rest of the developeroverse.

1) Run package installer to get the CORS library

Install-Package Microsoft.AspNet.WebApi.Cors (This took me 11.26 seconds btw.  Just sayin.)

2) Add code to webApiConfig (20s)

 

using System.Web.Http;
namespace WebService
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // New code
            config.EnableCors();

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

 

3) Hit the F5 key as hard as you can (this makes it run faster) (1s)

Try to invoke your service from the client again and lean back to savor as your service works this time!

 

*no CORS Light Beer was harmed during the authoring of this post

 

 

Richard Strickland

Leave a Reply

Your email address will not be published. Required fields are marked *