[英]Cors Error - MVC and Web API
我有一個 MVC 應用程序,它也使用 webapi2。 要調用 api 服務,我正在使用 jquery ajax,如下所示。
$.ajax({
url: GetBaseURL() + '/api/MyController/PutMethod',
type: 'put',
data: dataObject,
contentType: 'application/json',
timeout: AJAX_TIMEOUT,
success: function () {
self.CallOtherFunction();
});
並且函數 getbaseURL 返回 content.url("~") 雖然這種方法在某些頁面上有效,但它會拋出“跨源請求被阻止:相同的源策略不允許讀取http://api/MyController/ 上的遠程資源PutMethod ”錯誤。
我曾嘗試在 cors 上搜索,但無法理解為什么我會面臨此錯誤,即使我在一個解決方案下同時擁有 MVC 和 Webapi,並通過 Visual Studio 運行。
幫助表示贊賞。 謝謝。
問題出在您的 WebApi 中。 項目可以在同一個解決方案中,只有端口可以不同,你會得到 CORS 錯誤。 要解決 WebApi 問題,您可以閱讀這篇文章: http : //www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api
如果您在 mvc 中調用 api 時遇到此錯誤,請按照以下步驟操作
第 1 步:將此標簽放在 system.webServer 標簽下的 api 中的web.config文件中。
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*"/>
<add name="Access-Control-Allow-Headers" value="Content-Type, X-Your-Extra-Header-Key"/>
<add name="Access-Control-Allow-Methods" value="GET,POST,PUT,DELETE,OPTIONS"/>
<add name="Access-Control-Allow-Credentials" value="true"/>
</customHeaders>
</httpProtocol>
</system.webServer>
第 2 步 - 將其放入 webapi 應用程序中的global.asax.cs文件中
protected void Application_BeginRequest()
{
if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS")
{
Response.End();
Response.Flush();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.