C#WEB API CORS不起作用 [英] C# WEB API CORS does not work

查看:89
本文介绍了C#WEB API CORS不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

与CORS搏斗.我有一个网站正在对使用C#构建的WEB API进行简单的XmlHttpRequest.

Fighting with CORS. I have a site that is making a simple XmlHttpRequest to a WEB API I built in C#.

    var xhr = new XMLHttpRequest();
    xhr.open("GET","https://server/controller/method", true);
    xhr.send();

在我的web.config中,我已执行以下操作:

In my web.config I have done the following:

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

我还尝试安装Nuget软件包并在WebApiConfig.cs中执行以下操作

I have also tried installing the Nuget package and doing the following in my WebApiConfig.cs

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

尽管做出了这些努力,CORS仍然无法正常工作.在FireFox控制台中,出现以下错误:

Despite these efforts, CORS still does not work. In the FireFox console, I get the following error:

跨域请求被阻止:相同来源策略"不允许读取 https://server 上的远程资源.可以通过将资源移至同一域或启用CORS来解决此问题.

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://server. This can be fixed by moving the resource to the same domain or enabling CORS.

IE也只是失败而没有给出错误.

IE also just fails and gives no error.

根据我读过的所有内容,这些解决方案之一应该有效,但它们却无效.是否需要在客户端JavaScript中启用/更改某些内容?在Visual Studio IIS Express上的localhost:PortNumber上运行它时,CORS是否不起作用?我想念什么?

According to everything I have read, one of these solutions should work, yet they don't. Does something need to be enabled/changed in the client JavaScript? Does CORS not work when you run it in Visual Studio IIS Express on localhost:PortNumber? What am I missing?

推荐答案

在客户端JavaScript代码中,您可以尝试添加以下内容:

In your client JavaScript code, you could try adding this:

xhr.withCredentials = true;

Firefox CORS请求中所述尽管有标头,跨域请求仍被阻止" :

否则,Firefox在发出请求时无法使用客户端证书

otherwise Firefox failed to use the client cert when making the request

但是,如果您对客户端代码进行了更改,则还需要更改服务器端代码,以使 Access-Control-Allow-Origin 的值不是 *.有几种方法可以做到这一点……

However if you make that change to your client code, you’ll also need to change your server-side code so the value of Access-Control-Allow-Origin is not *. There are a few ways to do that…

通过IIS配置,您可以使用

From IIS config, you can do it with the URL Rewrite Module by adding the following to your Web.config or ApplicationHost.config file in %SystemDrive%\inetpub\wwwroot\.

<configuration> 
    <system.webServer> 
        <rewrite> 
            <outboundRules> 
                <rule name="Make Access-Control-Allow-Origin echo Origin"> 
                    <match serverVariable="RESPONSE_Access-Control-Allow-Origin"
                           pattern=".+" negate="true" /> 
                    <action type="Rewrite" value="{HTTP_ORIGIN}" /> 
                </rule> 
            </outboundRules> 
        </rewrite> 
    </system.webServer> 
</configuration>

如果上述方法不起作用,则可以在

If the above doesn’t work, then you can try the version in the answer over at CORS in IIS issue with credentials and wildcard in Access-Control-Allow-Origin.

另一种方法是在> global.asax 或其他适用于您的服务的代码,添加如下内容:

Another way to do it is, in the global.asax or other code for your service, add something like this:

if (ValidateRequest()) {
    Response.Headers.Remove("Access-Control-Allow-Origin");
    Response.AddHeader("Access-Control-Allow-Origin", Request.Headers["origin"]);
    Response.Headers.Remove("Access-Control-Allow-Credentials");
    Response.AddHeader("Access-Control-Allow-Credentials", "true");
    Response.Headers.Remove("Access-Control-Allow-Methods");
    Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
}

...其中最重要的部分是这样:

...the most important part of that being this:

Response.AddHeader("Access-Control-Allow-Origin", Request.Headers["origin"]);

如果这些都不起作用,请尝试使用以下方法 Microsoft.AspNet.WebApi.Cors .

And if neither of those work, try an approach using Microsoft.AspNet.WebApi.Cors.

这篇关于C#WEB API CORS不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆