.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”。

 

 

posted @ 2019-06-25 16:49  ken.  阅读(783)  评论(0编辑  收藏  举报