![](/img/trans.png)
[英]CORS Issue: C# API requests work for one domain, but not to the other
[英]Angular/C# CORS Issue
我將客戶端托管在localhost:8080 /上,將服務器托管在localhost:44302 /
我正在嘗試鏈接到后端,但出現了CORS問題。 以下是我的Angular http請求
$http.post(url, data, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST, OPTIONS'
}
}).success(function (response) {
// rest of the code
}).error(function (err, status) {
// rest of the code
});
在用C#編寫的服務器端,我對響應進行了以下設置
Response.ContentType = "application/json";
Response.AddHeader("Access-Control-Allow-Origin", "*");
Response.AddHeader("Access-Control-Allow-Methods", "POST, OPTIONS");
即使設置了這些,我仍然收到以下錯誤
XMLHttpRequest無法加載https:// localhost:44302 / some_uri 。 所請求的資源上沒有“ Access-Control-Allow-Origin”標頭。 因此,不允許訪問源' http:// localhost:8080 '。 響應的HTTP狀態碼為400。
我想念什么?
您不需要從AngularJS發送任何其他標頭。 飛行前請求將自動為您提出。
要啟用Web API中的所有跨域請求,您可以執行以下操作:
將以下代碼添加到WebApiConfig.cs:
var corsAttr = new EnableCorsAttribute("*", "*", "*"); config.EnableCors(corsAttr);
充分了解CORS值得花幾分鍾的時間。 我建議在這里閱讀深入的教程:
http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api
在應用程序級別服務器端執行此操作,無需在客戶端應用程序中進行任何更改
步驟1:安裝包Microsoft.AspNet.WebApi.Cors
第2步:從HttpConfiguration對象中,您可以啟用cors-適用於整個應用程序
public static void Register(HttpConfiguration config)
{
// New code
config.EnableCors();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
備用 :
第3步:轉到控制器,將其添加到以下屬性-僅適用於TestController
// Allow CORS for all origins. (Caution!)
[EnableCors(origins: "*", headers: "*", methods: "*")]
范例 :
[EnableCors(origins: "http://mywebclient.azurewebsites.net", headers: "*", methods: "*")]
public class TestController : ApiController
{
// Controller methods not shown...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.