C# 在 Web API 2 中启用 CORS

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18619656/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 12:46:15  来源:igfitidea点击:

Enable CORS in Web API 2

c#asp.net-web-apicors

提问by Gaui

I have client and a server running on different ports. The server is running Web API 2 (v5.0.0-rc1).

我有在不同端口上运行的客户端和服务器。服务器正在运行Web API 2 (v5.0.0-rc1)

I tried installing the Microsoft ASP.NET Web API Cross-Origin Support packageand enabled it in WebApiConfig.cs. It gives me the EnableCors()function, so the package was installed correctly.

我尝试安装Microsoft ASP.NET Web API 跨域支持包并在WebApiConfig.cs. 它为我提供了该EnableCors()功能,因此该软件包已正确安装。

Here you can see my Register()function in WebApiConfig.cs:

在这里你可以看到我的Register()功能WebApiConfig.cs

public static void Register(HttpConfiguration config)
{
    config.MapHttpAttributeRoutes();

    var cors = new EnableCorsAttribute("*", "*", "*");
    config.EnableCors(cors);
}

GETrequests work fine. But when sending POST, I get the following:

GET请求工作正常。但是在发送时POST,我得到以下信息:

OPTIONS http://localhost:19357/api/v1/rooms? 404 (Not Found) angular.js:10159
OPTIONS http://localhost:19357/api/v1/rooms? Origin http://localhost:8000 is not allowed by Access-Control-Allow-Origin. angular.js:10159
XMLHttpRequest cannot load http://localhost:19357/api/v1/rooms. Origin http://localhost:8000 is not allowed by Access-Control-Allow-Origin.

According to Fiddler it only sends the OPTIONSrequest. It doesn't issue the POSTafterwards.

根据 Fiddler,它只发送OPTIONS请求。它不发出POST事后。

So I'm guessing the config.EnableCors(cors);in the WebApiConfig.csisn't doing anything, which leads to the server denying the client/browser to send a POSTrequest.

所以我猜测config.EnableCors(cors);inWebApiConfig.cs没有做任何事情,这会导致服务器拒绝客户端/浏览器发送POST请求。

Do you have any idea how to solve this problem?

你知道如何解决这个问题吗?

EDIT 05.09.13This has been fixed in 5.0.0-rtm-130905

编辑 05.09.13这已在 5.0.0-rtm-130905 中得到修复

采纳答案by Gaui

I'm most definitely hitting this issuewith attribute routing. The issuewas fixedas of 5.0.0-rtm-130905. But still, you can try out the nightly buildswhich will most certainly have the fix.

我肯定会通过属性路由解决这个问题该问题已从 5.0.0-rtm-130905开始修复。但是,您仍然可以尝试夜间构建,这肯定会得到修复。

To add nightlies to your NuGet package source, go to Tools -> Library Package Manager -> Package Manager Settingsand add the following URL under Package Sources: http://myget.org/F/aspnetwebstacknightly

要将 nightlies 添加到 NuGet 包源,请转到Tools -> Library Package Manager -> Package Manager Settings并添加以下 URL Package Sourceshttp: //myget.org/F/aspnetwebstacknightly

回答by Sudhanshu Mishra

CORS works absolutely fine in Microsoft.AspNet.WebApi.Corsversion 5.2.2. The following steps configured CORS like a charm for me:

CORS 在Microsoft.AspNet.WebApi.Cors5.2.2 版本中工作得非常好。以下步骤将 CORS 配置为对我来说很有吸引力:

  1. Install-Package Microsoft.AspNet.WebApi.Cors -Version "5.2.2"// run from Package manager console
  2. In Global.asax, add the following line: BEFORE ANY MVC ROUTE REGISTRATIONS

    GlobalConfiguration.Configure(WebApiConfig.Register);
    
  3. In the WebApiConfigRegister method, have the following code:

    public static void Register(HttpConfiguration config)
    {
        config.EnableCors();
        config.MapHttpAttributeRoutes();
    }
    
  1. Install-Package Microsoft.AspNet.WebApi.Cors -Version "5.2.2"// 从包管理器控制台运行
  2. 在 Global.asax 中,添加以下行:BEFORE ANY MVC ROUTE REGISTRATIONS

    GlobalConfiguration.Configure(WebApiConfig.Register);
    
  3. WebApiConfigRegister 方法中,有以下代码:

    public static void Register(HttpConfiguration config)
    {
        config.EnableCors();
        config.MapHttpAttributeRoutes();
    }
    

In the web.config, the following handler must be the first one in the pipeline:

在 web.config 中,以下处理程序必须是管道中的第一个:

<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />

In the controller derived from ApiController, add the EnableCorsAttribute:

在派生自 的控制器中ApiController,添加EnableCorsAttribute

[EnableCors(origins: "*", headers: "*", methods: "*")] // tune to your needs
[RoutePrefix("")]
public class MyController : ApiController

That should set you up nicely!

那应该很好地设置你!

回答by Mariusz

Late reply for future reference. What was working for me was enabling it by nuget and then adding custom headers into web.config.

迟回复以备将来参考。对我有用的是通过 nuget 启用它,然后将自定义标头添加到 web.config 中。

回答by Mosharaf Hossain

I didn't need to install any package. Just a simple change in your WebAPI project's web.config is working great:

我不需要安装任何软件包。只需对您的 WebAPI 项目的 web.config 进行一个简单的更改就可以很好地工作:

<system.webServer>
    <httpProtocol>
        <customHeaders>
            <add name="Access-Control-Allow-Origin" value="*" />
        </customHeaders>
    </httpProtocol>
</system.webServer>

Credit goes to: Using CORS in ASP.NET WebAPI Without Being a Rocket Scientist

归功于在 ASP.NET WebAPI 中使用 CORS 而不是火箭科学家

回答by Lankymart

For reference using the [EnableCors()]approach will not work if you intercept the Message Pipeline using a DelegatingHandler. In my case was checking for an Authorizationheader in the request and handling it accordingly before the routing was even invoked, which meant my request was getting processed earlier in the pipeline so the [EnableCors()]had no effect.

对于使用的参考[EnableCors()]方法将如果拦截消息流水线使用不起作用DelegatingHandler。在我的情况下,正在检查Authorization请求中的标头并在调用路由之前相应地处理它,这意味着我的请求在管道中更早地得到处理,因此[EnableCors()]没有任何影响。

In the end found an example CrossDomainHandlerclass(credit to shaunxufor the Gist)which handles the CORS for me in the pipeline and to use it is as simple as adding another message handler to the pipeline.

最后找到了一个示例CrossDomainHandler(归功于shaunxuGist,它在管道中为我处理 CORS,使用它就像向管道添加另一个消息处理程序一样简单。

public class CrossDomainHandler : DelegatingHandler
    {
        const string Origin = "Origin";
        const string AccessControlRequestMethod = "Access-Control-Request-Method";
        const string AccessControlRequestHeaders = "Access-Control-Request-Headers";
        const string AccessControlAllowOrigin = "Access-Control-Allow-Origin";
        const string AccessControlAllowMethods = "Access-Control-Allow-Methods";
        const string AccessControlAllowHeaders = "Access-Control-Allow-Headers";

        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            bool isCorsRequest = request.Headers.Contains(Origin);
            bool isPreflightRequest = request.Method == HttpMethod.Options;
            if (isCorsRequest)
            {
                if (isPreflightRequest)
                {
                    return Task.Factory.StartNew(() =>
                    {
                        HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
                        response.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First());

                        string accessControlRequestMethod = request.Headers.GetValues(AccessControlRequestMethod).FirstOrDefault();
                        if (accessControlRequestMethod != null)
                        {
                            response.Headers.Add(AccessControlAllowMethods, accessControlRequestMethod);
                        }

                        string requestedHeaders = string.Join(", ", request.Headers.GetValues(AccessControlRequestHeaders));
                        if (!string.IsNullOrEmpty(requestedHeaders))
                        {
                            response.Headers.Add(AccessControlAllowHeaders, requestedHeaders);
                        }

                        return response;
                    }, cancellationToken);
                }
                else
                {
                    return base.SendAsync(request, cancellationToken).ContinueWith(t =>
                    {
                        HttpResponseMessage resp = t.Result;
                        resp.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First());
                        return resp;
                    });
                }
            }
            else
            {
                return base.SendAsync(request, cancellationToken);
            }
        }
    }

To use it add it to the list of registered message handlers

要使用它,请将其添加到已注册的消息处理程序列表中

config.MessageHandlers.Add(new CrossDomainHandler());

Any preflight requests by the Browser are handled and passed on, meaning I didn't need to implement an [HttpOptions]IHttpActionResultmethod on the Controller.

浏览器的任何预检请求都会被处理和传递,这意味着我不需要[HttpOptions]IHttpActionResult在控制器上实现一个方法。

回答by Vikas

 var cors = new EnableCorsAttribute("*","*","*");
 config.EnableCors(cors);

 var constraints = new {httpMethod = new HttpMethodConstraint(HttpMethod.Options)};
 config.Routes.IgnoreRoute("OPTIONS", "*pathInfo",constraints);

回答by tno2007

Make sure that you are accessing the WebAPI through HTTPS.

确保您通过 HTTPS 访问 WebAPI。

I also enabled cors in the WebApi.config.

我还在 WebApi.config 中启用了 cors。

var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);

But my CORS request did not work until I used HTTPS urls.

但是我的 CORS 请求在我使用 HTTPS url 之前不起作用。

回答by user12319595

To enable CORS, 1.Go to App_Start folder. 2.add the namespace 'using System.Web.Http.Cors'; 3.Open the WebApiConfig.cs file and type the following in a static method.

要启用 CORS, 1. 转到 App_Start 文件夹。2.添加命名空间'using System.Web.Http.Cors';3.打开WebApiConfig.cs文件,在静态方法中输入以下内容。

config.EnableCors(new EnableCorsAttribute("https://localhost:44328",headers:"*", methods:"*"));