通过Ajax远程调用WebService(ASP.NET)

时间:2013-07-03 16:27:10

标签: .net ajax web-services asmx access-control

客户 - AJAX

    $.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 + "'");
        }
    });

SERVER - 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");
}

SERVER - 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时,它会直接转到result = null的成功回调。调试器出现此错误:

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

1 个答案:

答案 0 :(得分:0)

请尝试在Ajax调用中将 url 更改为 origin