cors實現跨域(.net和jquery)


本文引用自:http://blog.csdn.net/xuwei_xuwei/article/details/29845865

客戶端

一個jquery cors請求例子:
$.ajax({  
            type: 'post',  
            crossDomain: true,  
            url: 'http://your.url.com/admin/login',  
            data: {  
                UserName: $('#name:text', this.el).val(),  
                PassWord: $('#Password:password', this.el).val()  
            },  
            dataType:'json',  
            xhrFields: {  
                'Access-Control-Allow-Origin': '*'
            },  
            success: function(data, textStatus, jqXHR){  
                console.log("getAllResponseHeaders:"+jqXHR.getAllResponseHeaders());  
                console.dir(jqXHR);  
                Backbone.history.navigate("#booklist",true);  
            }  
        });  

服務端

.net后端實現cors有3種方法

1.服務端配置(iis7為例)

在項目的web.config文件中添加下面的代碼即可
//全局配置
<?xml version="1.0" encoding="utf-8"?>
<configuration>
 <system.webServer>
   <httpProtocol>
     <customHeaders>
       <add name="Access-Control-Allow-Origin" value="*" />
     </customHeaders>
   </httpProtocol>
 </system.webServer>
</configuration>

2.asp.net 中,在每次對客戶端的響應時,添加如下代碼即可

Response.AppendHeader("Access-Control-Allow-Origin", "*");

3.ASP.NET Web API中,要做如下配置

ASP.NET Web API 2 支持 CORS,要支持cors,請先用vs自帶的nuget安裝 Microsoft.AspNet.WebApi.Cors包
然后在mvc項目中添加如下代碼
目錄 App_Start 文件 WebApiConfig
public static void Register(HttpConfiguration config)
{
    // 其他配置,
//下面是全局配置
//var cors = new EnableCorsAttribute("www.example.com", "*", "*");
//config.EnableCors(cors);
    config.EnableCors();
}
在對用的apicontrol通過特性聲明對應的origin,headers,methods
//類級別設置
[EnableCors(origins: "http://example.com", headers: "*", methods: "*")]
public class TestController : ApiController
{
    // Controller methods not shown...
}
//方法級別設置
public class ItemsController : ApiController
{
    public HttpResponseMessage GetAll() { ... }


    [EnableCors(origins: "http://www.example.com", headers: "*", methods: "*")]
    public HttpResponseMessage GetItem(int id) { ... }


    public HttpResponseMessage Post() { ... }
    public HttpResponseMessage PutItem(int id) { ... }
}
ok,.net服務端的配置上述3中任選一種即可
其他服務器和語言關於cors的配置請參考下面地址:http://enable-cors.org/server.html
如圖:


原文地址:http://enable-cors.org/server_iis7.html
                    http://enable-cors.org/server_aspnet.html
                    http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api


免責聲明!

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



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