簡體   English   中英

Access-Control-Allow-Origin 在標頭請求 ASP.NET Web API 上出現兩次

[英]Access-Control-Allow-Origin appearing twice on header request ASP.NET Web API

我的 ASP.NET Web API 控制器之一。 我的客戶端應用程序返回以下錯誤:

對預檢請求的響應未通過訪問控制檢查:“Access-Control-Allow-Origin”標頭包含多個值“*、*”,但只允許一個。 因此,不允許訪問源“ http://localhost:8100 ”。

我認識到發生此錯誤是因為標頭包含多個值。 當通過 Chrome 調用 API 時,我可以在“響應標頭”中看到這一點,如下所示:

HTTP/1.1 200 正常

緩存控制:無緩存

內容長度:0

服務器:Microsoft-IIS/8.0

訪問控制允許方法:GET、POST

訪問控制允許來源:*

Access-Control-Allow-Headers:Content-Type、Accept、Pragma、Cache-Control、Authorization

訪問控制最大年齡:1728000

X-Powered-By: ASP.NET

訪問控制允許來源:*

訪問控制允許方法:GET、POST、OPTIONS、PUT、DELETE

Access-Control-Allow-Headers:Origin、X-Requested-With、Content-Type、Accept、Authorization

設置 Cookie:ARRAffinity=ef9b3770b61f10f9696b0dedcb39a7f47a83c0e4d6cdbf367f3149482592ef06;Path=/;HttpOnly;Domain=seirse.azurewebsites.net

如您所見,它顯然存在兩次。

我遇到的問題是我啟用 CORS 的唯一地方是通過我的應用程序中的 web.config,例如

<httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Methods" value="GET, POST, OPTIONS, PUT, DELETE" />
        <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept, Authorization" />
      </customHeaders>
    </httpProtocol>

我已經 100% 確定我沒有通過 Startup.cs 或在控制器中啟用 CORS。

據我所知,控制器沒有什么不尋常的地方:

// GET: api/Address/all
[HttpGet]
public AddressResultModel All()
{
    try
    {
        var userId = _accountService.GetUserId(Request);
        return _customerRepository.GetAddresses(userId);
    }
    catch (Exception)
    {
        return null;
    }
}

任何想法可能是什么問題?

事實證明,我的Global.asax.cs中有代碼,它為 OPTIONS HTTP 請求的響應添加了標頭。

我添加此代碼的原因是由於一個單獨的問題,即我收到 OPTIONS HTTP 請求的“405 Method Not Allowed”錯誤消息。

為了解決這兩個問題,我刪除了添加額外標題的代碼並將其修剪為:

protected void Application_BeginRequest()
{
    if (Request.Headers.AllKeys.Contains("Origin", StringComparer.CurrentCultureIgnoreCase)
        && Request.HttpMethod == "OPTIONS")
    {
        Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, Pragma, Cache-Control, Authorization ");
        Response.End();
    }
}

我不確定為什么這解決了問題。

就我而言,我收到此錯誤是因為我的端點直接從另一個請求返回響應,因此我的 cors 過濾器使用現有過濾器將新標頭添加到收到的響應中:

@GetMapping
public ResponseEntity getOmdbSearch(@RequestParam Map<String, String> requestParamMap, Principal principal) {
... ... ...

// Here an error !
return restTemplate.getForEntity(uriComponentsBuilder.toUriString(), String.class);
}

我通過僅返回結果來修復它:

@GetMapping
public String getOmdbSearch(@RequestParam Map<String, String> requestParamMap,
                            Principal principal) {
    ResponseEntity<String> response = restTemplate.getForEntity(uriComponentsBuilder.toUriString(), String.class);
    return response.getBody();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM