How to use CORS in ASP.NET Web API SelfHost applications?

Add class

public class CustomHeaderHandler : DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
    {
    return base.SendAsync(request, cancellationToken)
        .ContinueWith((task) =>
        {
            HttpResponseMessage response = task.Result;
            response.Headers.Add("Access-Control-Allow-Origin", "*");
            return response;
        });
    }
}

and register it in configuration

var config = new HttpSelfHostConfiguration("http://localhost:5555");    
config.MessageHandlers.Add(new CustomHeaderHandler());

The WebAPIContrib project has a simple Cors MessageHandler. Or if you are looking for more sophisticated solution, the Thinktecture.IdentityModel project has CORS support.