.net MVC下跨域Ajax請求(CORS)


二、CROS (Cross-origin Resource Sharing)

  CROS相當於一種協議,由瀏覽器、服務端共同完成安全驗證,進行安全的跨域資源共享。對於開發人員來說就跟在本站AJAX請求一樣,瀏覽器會自動判斷是否使用CROS。

  客戶端:

 1 <script type="text/javascript">
 2     function TestCors() {
 3         $.ajax({
 4             type: "GET",
 5             url: "http://hamp-sz-0104/MVC/Books/Test",
 6             dataType: "json",
 7             success: function (obj) {
 8                 alert(obj.Name);
 9             }
10         })
11     }
12 </script>

  服務端:

1     public class BooksController : Controller
2     {
3         public ActionResult Test()
4         {
5             return Json(new { Name = "CORS" },JsonRequestBehavior.AllowGet);
6         }
7     }

  服務端配置:需要給允許CORS請求的消息設置Access-Control-Allow-Origin header值,或使用“*”授權任何域名可訪問

1 <system.webServer>
2   <httpProtocol>
3     <customHeaders>
4       <add name="Access-Control-Allow-Origin" value="http://localhost:3794"/>
5     </customHeaders>
6   </httpProtocol>
7   </system.webServer></configuration>

  若無配置,瀏覽器會收到如下錯誤提示:SEC7120: [CORS] 原點“http://localhost:3794”未在“http://hamp-sz-0104/MVC/Books/JsonpTest”的 cross-origin 資源的 Access-Control-Allow-Origin response header 中找到“http://localhost:3794”。

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM