Integrating LightInject as a custom CORS provider in ASP.NET Web API

Cross-Origin Resource Sharing, or CORS (MDN link) is a method of HTTP access control to restrict access to resources hosted on other domains, especially from within scripts. I'm going to assume you are all relatively familiar with the workings and implications of CORS.

In ASP.NET Web API, CORS support is provided by the Microsoft.AspNet.WebApi.Cors NuGet package. Simply install it, define your policy in attributes and off you go. Or, you can define some custom types and tweak the HttpConfiguration directly to automatically add a policy, but that hurts the clarity of your code and makes updates a little trickier. What's even better? Resolving CORS directly from your IoC container!

For LightInject users, I have just published a new NuGet package to integrate LightInject and ASP.NET Web API CORS support. So how's it work? Real simple:

protected void Application_Start()  
{
    var container = new ServiceContainer();
    container.RegisterApiControllers();
    container.RegisterCorsPolicies(); //important!
    //register other services
    container.EnableCors(GlobalConfiguration.Configuration); //important!
    container.EnableWebApi(GlobalConfiguration.Configuration);              
}

The call to RegisterCorsPolicies() will automatically find and register any custom CORS policy types in your assembly and register them with LightInject. Then EnableCors(HttpConfiguration) will automatically create a simple provider factory, register it with ASP.NET, and enable CORS for the config. And that's it!

You can find more detailed information in the online documentation.

As always, you can find full source code on GitHub and I'm happy to accept requests, issues and pulls.

Comments

comments powered by Disqus