【问题标题】:Remotely Calling WebService via Ajax (ASP.NET)通过 Ajax (ASP.NET) 远程调用 WebService
【发布时间】:2013-07-01 11:00:21
【问题描述】:

客户端 - 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 + "'");
        }
    });

服务器 - 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 时,它会直接进入 result = null 的成功回调。这个错误出现在调试器上:

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

【问题讨论】:

  • 您使用的是什么版本的 IIS?
  • 您还可以捕捉到实际的请求/响应并检查是否确实添加了标头吗?

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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-26
    • 1970-01-01
    相关资源
    最近更新 更多