2013-07-03 66 views
3

客戶端呼叫的WebService - AJAX遠程通過Ajax(ASP.NET)

$.ajax({ 
     type: "POST", 
     url: 'http://www.site.com/Service.asmx/Method', 
     data: "{ 'user': 'sampleuser', 'pass': '123456' }", 
     contentType: "application/json; charset=utf-8", 
     dataType: "json", 
     async: true, 
     success: function (result) { 
      alert("result: '" + result+ "'"); 
     }, 
     error: function (e) { 
      alert("error: '" + e + "'"); 
     } 
    }); 

服務器 - Global.asax中

protected void Application_BeginRequest(object sender, EventArgs e) 
{ 
    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");  
    // HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "http://AllowedDomain.com"); 
} 

服務器 - WEB.CONFIG

<httpProtocol> 
    <customHeaders> 
    <add name="Access-Control-Allow-Origin" value="*" /> 
    <add name="Access-Control-Allow-Headers" value="Content-Type, Authorization" /> 
    <add name="Access-Control-Allow-Methods" value="PUT, GET, POST, DELETE, OPTIONS" /> 
    </customHeaders> 
</httpProtocol> 

服務器 - 服務 - C#

[WebMethod(EnableSession = true)] 
public string Method(string user, string pass) 
{ 
    // logic 
} 

什麼情況是,當AJAX調用,它直接與結果= null,則成功回調。這個錯誤出現在調試器:

XMLHttpRequest cannot load http://www.site.com/Service.asmx/Method. 
Origin http://localhost is not allowed by Access-Control-Allow-Origin. 
+0

您使用的是哪個版本的IIS? –

+0

你也可以捕獲實際的請求/響應,並檢查頭是否實際添加? –

回答

0

請嘗試更改網址在Ajax調用起源