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?
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.
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: "*"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With