Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'am trying to use ASP.NET Web API Selfhosted application with CORS, but getting an error:

XMLHttpRequest cannot load http://localhost:5555/api/product. Origin null is not allowed by Access-Control-Allow-Origin.

How can I handle it?

like image 648
Denis Bednov Avatar asked Jun 24 '13 12:06

Denis Bednov


3 Answers

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());
like image 117
Nerve Avatar answered Oct 12 '22 01:10

Nerve


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

like image 42
Darrel Miller Avatar answered Oct 12 '22 00:10

Darrel Miller


You can also do that by installing Microsoft.AspNet.WebApi.Cors package from Nuget.

This will allow your API to enable Cross-Origin Resource Sharing (CORS). You can do it like:

 var config = new HttpSelfHostConfiguration(_baseAddress);
 config.EnableCors(new EnableCorsAttribute("*", headers: "*", methods: "*"));
like image 34
Mukesh Rawat Avatar answered Oct 12 '22 01:10

Mukesh Rawat