多个Access-Control-Allow-Origin标头

时间:2018-02-07 22:42:30

标签: c# asp.net-mvc asp.net-web-api xmlhttprequest cors

供我参考,我使用的是Visual Studio 2017和Windows 10.

我有一个带有用户帐户的web api和相应的Web应用程序。当我尝试登录时遇到错误,该错误表示存在No Access-Control-Allow-Origin标头。我找到了一个指南,向我介绍了如何设置CORS。这是我使用的指南。

https://social.technet.microsoft.com/wiki/contents/articles/33771.fix-to-no-access-control-allow-origin-header-is-present-or-working-with-cross-origin-request-in-asp-net-web-api.aspx

在我的WebApiConfig文件中,我有这段代码

public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
        // Configure Web API to use only bearer token authentication.
        config.SuppressDefaultHostAuthentication();
        config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

        // Web API routes
        config.MapHttpAttributeRoutes();

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

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

在我的AccountController文件中,我添加了顶部的EnableCors。

[EnableCors(origins: "*", headers: "*", methods: "*")]
[Authorize]
[RoutePrefix("api/Account")]

最后,在我的Web.config文件中,我添加了以下内容:

<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Headers" value="Content-Type" />
    <add name="Access-Control-Allow-Methods" value="GET,POST,PUT,DELETE,OPTIONS" />
    <add name="Access-Control-Allow-Credentials" value="true" />
  </customHeaders>
</httpProtocol>

这解决了我的登录问题,但是我的GETS都没有工作。以下是GET函数的示例:

jQuery.support.cors = true;
    if (window.XMLHttpRequest) {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.open("GET", 'http://localhost:60690/api/ProfilePicture?Username=' + username, false);
        xmlhttp.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
        xmlhttp.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('accessToken'));
        xmlhttp.send();
        if (xmlhttp.status == 200) {
            returnValue = jQuery.parseJSON(xmlhttp.responseText);
        }
    }

GET抛出一个错误,表示&#34; CORS响应&#34;不允许多个访问 - 控制 - 允许 - 来源标头。我不知道我在哪里有多个Access-Control-Allow-Origin标头。我应该在哪里看?

更新1

找到一些有趣的东西。我使用Fiddler观察后台和GET函数中发生的一切,导致错误我在标题中看到了这一点:

enter image description here

所以&#34; Access-Control-Allow-Origin:*&#34;肯定会出现两次,但问题是为什么。我搜索了所有代码,我只宣布了一次。如果我删除该行,它会破坏登录页面,所以我必须将其保留。

1 个答案:

答案 0 :(得分:1)

我想我想出来了。我进入了WebApiConfig文件并将有关CORS的部分更改为:

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

然后我从我的Controller中删除了EnableCors部分,它又开始了。我在GET电话上仍然收到错误,但我从两个错误变为一个错误,所以我猜它会有进展。