简体   繁体   English

Web API 2 Cors无法正常工作

[英]web api 2 cors not working

I create a web service on Web API and try to use it from angular 2 application. 我在Web API上创建了一个Web服务,并尝试从angular 2应用程序中使用它。 I install Microsoft.AspNet.WebApi.Core 5.2.3 and configure it to allow cors. 我安装Microsoft.AspNet.WebApi.Core 5.2.3并将其配置为允许cors。 It hosted on local IIS at localhost/RestfulAPI 它托管在本地IIS的localhost / RestfulAPI上

WebApiConfig WebApiConfig

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        config.Routes.MapHttpRoute(
            name: "DefaultApi 2",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        var cors = new EnableCorsAttribute("*", "*", "*"); // origins, headers, methods
        config.EnableCors(cors);
    }
}

controller 调节器

[HttpGet]
[Route("api/product/details")]
public async Task<IHttpActionResult> GetProductsDetails([FromUri]ProductSearch model)
{
    using (var unitOfWork = Factory.Create())
    {
        var products = (from p in await unitOfWork.GetProductsAsync(model?.CategoryID, model?.BrandID, model?.ProductStateID, null, model?.PartnerID,
                    true, model?.Code)
            orderby p.Code
            select p).ToArray();
        return return Json(products);
    }
}

But I'm still get error in browser. 但是我仍然在浏览器中出错。

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. 对预检请求的响应未通过访问控制检查:请求的资源上不存在“ Access-Control-Allow-Origin”标头。 Origin ' http://localhost:12012 ' is therefore not allowed access. 因此,不允许访问源“ http:// localhost:12012 ”。 The response had HTTP status code 404. 响应的HTTP状态码为404。

How could it be, that I enabled all cors, but it still not working? 我启用所有cors怎么可能,但仍然无法正常工作?

Upd.1. Upd.1。 I try to handle an options request like bellow 我尝试处理以下波纹管的期权要求

 public class PreflightRequestsHandler : DelegatingHandler
        {
            protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
            {
                if (request.Headers.Contains("Origin") && request.Method.Method.Equals("OPTIONS"))
                {
                    var response = new HttpResponseMessage { StatusCode = HttpStatusCode.OK };
                    // Define and add values to variables: origins, headers, methods (can be global)               
                    response.Headers.Add("Access-Control-Allow-Origin", "*");
                    response.Headers.Add("Access-Control-Allow-Headers", "*");
                    response.Headers.Add("Access-Control-Allow-Methods", "*");
                    var tsc = new TaskCompletionSource<HttpResponseMessage>();
                    tsc.SetResult(response);
                    return tsc.Task;
                }
                return base.SendAsync(request, cancellationToken);
            }

        }

But get an error: Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response. 但是出现错误:飞行前响应中Access-Control-Allow-Headers不允许请求标头字段Content-Type。

Make sure you are using Api controller instead of the plain controller which inherits from Apicontroller class. 确保您使用的是Api控制器,而不是从Apicontroller类继承的普通控制器。 I had same issue, then i figured out that i was using plain controller, i rectified it and i am not able to access and fetch the data from the api controller. 我遇到了同样的问题,然后我发现我使用的是普通控制器,我对其进行了纠正,但我无法从api控制器访问和获取数据。

You can try with below nuget 您可以尝试以下nuget

Nuget for CORS Nuget for CORS

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM