如何在ASP.NET Web API SelfHost应用程序中使用CORS?

Den*_*nov 4 cors asp.net-web-api

我试图使用带有CORS的ASP.NET Web API Selfhosted应用程序,但收到错误:

XMLHttpRequest无法加载http:// localhost:5555/api/product.Access-Control-Allow-Origin不允许使用null.

我该怎么处理?

Ner*_*rve 12

添加课程

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;
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

并在配置中注册它

var config = new HttpSelfHostConfiguration("http://localhost:5555");    
config.MessageHandlers.Add(new CustomHeaderHandler());
Run Code Online (Sandbox Code Playgroud)