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

I try to use the ASP.NET Web API Selfhosted application with CORS, but I get an error:

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

How can I handle this?

+4
source share
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 the configuration

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

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

+2
source

You can also do this by installing the 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: "*")); 
0
source

Source: https://habr.com/ru/post/1487877/


All Articles