概念:CORS是一個W3C標準,全稱是"跨域資源共享"(Cross-origin resource sharing)。它允許瀏覽器向跨源伺服器,發出XMLHttpRequest請求,從而克服了AJAX只能同源使用的限制。
現象:如請求出現:Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'xxxxx' is therefore.
WebApi開啟CORS設定分為2步:
Step1:開啟NuGet安裝Microsoft.AspNet.Cors 如圖:
Step2:WebApiConfig.cs設定開啟Cors,程式碼如下:
//跨域配置 config.EnableCors(new System.Web.Http.Cors.EnableCorsAttribute("*", "*", "*"));
即可解決Post跨域的問題,當然如果是Get請求是不需要設定跨域的,直接可以訪問。