How to make cross-domain/cross-origin calls with AngularJS, WebApi and CORS


 

CORS support is very easy to setup in WebApi, but the docs are outdated. They removed the parameterless constructor and didn’t update the docs. For testing purposes, you should just pass “*” for all three parameters.  In production you should limit to hosts that you want to be able to call your endpoint.

CODE: https://github.com/jonbgallant/AngularJS-WebApi-CORS/

Here’s what you need to do:

1. Nuget CORS: Microsoft.AspNet.WebApi.Cors – You need to include prerelease packages when you do a search.

image

2. Call EnableCors from WebApiConfig

public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
config.EnableCors(new EnableCorsAttribute(“*”, “*”, “*”));

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

3. Make $http calls from AngularJS or any other Spa framework.

return $http.post(‘http://localhost:45211/api/values/add/’, value);

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