'Access-Control-Allow-Origin' header 包含多个值'*, *',但只允许一个

The 'Access-Control-Allow-Origin' header contains multiple values '*, *', but only one is allowed

我正在使用 Angular 和 ASP.NET API。我面临的问题:当我在 API 代码中添加 CORS 时,它可以在 Internet Explorer 上运行,但不能在 Chrome 和 Firefox 上运行。

这里是错误:

XMLHttpRequest cannot load http://localhost:41028/api/values/abc. The 'Access-Control-Allow-Origin' header contains multiple values '*, *', but only one is allowed. Origin 'http://localhost:44796' is therefore not allowed access.

这是我在 web.config 文件中添加的代码:

<system.webServer>
...
<httpProtocol>
  <customHeaders>
      <!-- Adding the following custom HttpHeader will help prevent CORS errors -->
      <add name="Access-Control-Allow-Origin" value="*" />
      <add name="Access-Control-Allow-Headers" value="Content-Type" />
  </customHeaders>
</httpProtocol>
...
</system.webServer>

WebApiConfigFile.cs 文件中我添加了:

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

我是第一次使用 CORS。任何帮助将不胜感激。

Chrome 和 Firefox 使用 "OPTIONS" 动词进行所谓的飞行前检查。

因此,您必须将 "OPTIONS" 添加到 web.config 中允许的方法。您可能还必须向 Application_Begin 请求添加一些代码,就像这个答案所建议的那样: Handling CORS Preflight requests to ASP.NET MVC actions

以下是 CORS 的一些资源:

IIS hijacks CORS Preflight OPTIONS request

http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

您设置了两次 CORS。我认为这是问题所在。

请删除任何一个 CORS 设置。您可以将其从 web.configWebApiConfigFile.cs.

中删除

我遇到这个问题是因为我把 app.UseCors 放在了 ConfigureOAuth 之后。更改顺序修复问题。

    public void Configuration(IAppBuilder app)
    {
        HttpConfiguration config = new HttpConfiguration();

        app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
        ConfigureOAuth(app);

        WebApiConfig.Register(config);

        // Used to put this line after ConfigureAuth(app), 
        // app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

        app.UseWebApi(config);
    }

这是我的案例的详细信息:

  • 一开始我得到 Origin is not allowed in 'Access-Control-Allow-Origin', when calling \token.
  • L因此,我添加了包含 'Access-Control-Allow-Origin'、'Access-Control-Allow-headers'、'Access-Control-Allow-methods' 的 customHeader。它修复了 \token 请求。
  • 但是我在调​​用 detail api 时得到了重复的 'Access-Control-Allow-Origin'。有很多建议,比如this就是无法修复

我遇到了同样的问题。在我输入确切的域而不是 *(见下文)后,它对我有用。

var CorsAttribute = new EnableCorsAttribute("https://www.mywebsite.com","", ""); config.EnableCors(CorsAttribute);

为网络提供的所有其他解决方案API。此解决方案适用于将 webservice(.asmx) 用作 API

Global.asax.cs 文件的 begin_request 函数或 web.config 中删除 'Access-Control-Allow-Origin' 详细信息。因为这个设置只能在一个地方

我遇到了完全相同的错误,原因是

"Access-Control-Allow-Origin: *"

header 已经出现在 IIS HTTP 响应 Headers 列表中。 Example

从列表中删除它对我有用。