我有一個ASP.NET的Web API,它是由三個不同的SPA叫。我正在爲Web API使用Windows身份驗證。我最初試圖在Web.config這樣的配置CORS:使用PUT和DELETE有多個起源請求時如何解決的ASP.NET Web API CORS預檢問題?
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="http://localhost:63342" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE" />
<add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
<add name="Access-Control-Allow-Credentials" value="true" />
</customHeaders>
</httpProtocol>
這導致此問題的預檢:
Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin (...) is therefore not allowed access.
,我在Global.asax.cs中添加以下方法解決:
protected void Application_BeginRequest()
{
if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS")
{
Response.Flush();
}
}
這種做法非常完美的一個SPA。我想我可以去Web.config並添加像這樣的其他起源:
<add name="Access-Control-Allow-Origin" value="http://localhost:63342,http://localhost:63347,http://localhost:63345/>
但顯然這是不允許的。這將產生以下錯誤:
所以爲了嘗試解決這個問題,我改變了我的做法,而是決定嘗試在WebAPIConfig.cs配置CORS,在註冊的方法是這樣的:
var cors = new EnableCorsAttribute("http://localhost:63342,http://localhost:63347,http://localhost:63345", "Origin, X-Requested-With, Content-Type, Accept", "GET, POST, PUT, DELETE");
cors.SupportsCredentials = true;
config.EnableCors(cors);
我認爲這會工作,但現在我使用的時候PUT和DELETE請求,我不知道如何解決這個問題再有預檢錯誤。我調試了Application_BeginRequest方法,它仍在沖洗OPTIONS請求,所以我不知道是什麼導致了這個錯誤。有誰知道我可以如何解決這個問題?
編輯:
預檢錯誤的打印:
@Aravind對不起,我無法真正理解你提出的解決方案因爲SO由於某種原因使報價翻倍。你能否以另一種方式寫下來? –
您可以使用'new EnableCorsAttribute(「*」,「*」,「*」)來允許所有域和方法;'更好的方式來處理這個問題,就是使用ICorsPolicyProvider創建自己的自定義屬性並實現GetCorsPolicyAsync方法。 – Paresh
@Paresh但我不能使用*,因爲我使用的是Windows身份驗證,它不兼容。除此之外,我只想讓這三個網址。 –