简体   繁体   English

如何使用Ajax调用WCF服务

[英]How to call wcf service using ajax

I'm trying to call a WCF service from ajax call. 我正在尝试从ajax调用中调用WCF服务。 This is my ajax call: 这是我的ajax电话:

     $j.ajax(
            {
                type: "POST",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                context: this,
                async: false,
                url: appServicePath + "Student/GetRolesByUserId",
                data: JSON.stringify({ "userId": userId }),
                success: this.getRolesByIdResponse,
                error: this.getRolesByIdFailure
            }
        );

when I test my service using Fiddler I'm able to get the roles of the user that I'm passing its value from ajax but when I call the service from my application I get an error: 405 Method Not Allowed. 当我使用Fiddler测试服务时,我可以从Ajax传递其值来获得用户的角色,但是当我从应用程序中调用服务时,我得到一个错误:405 Method Not Allowed。 What am I doing wrong? 我究竟做错了什么?

According to your description, I think this problem is due to cross-domain, the problem generates an OPTIONS request, So the method is not allowed. 根据您的描述,我认为此问题是由于跨域引起的,该问题生成了OPTIONS请求,因此该方法是不允许的。 If you put the script in the same domain as the webservice, you won't have this problem. 如果将脚本与Web服务放在同一域中,则不会出现此问题。

IIS物理路径

Here is Http 405 method document. 这是Http 405方法文件。

https://tools.ietf.org/html/rfc7231#section-6.5.5 https://tools.ietf.org/html/rfc7231#section-6.5.5

You now need to turn on cross-domain support for a WCF application hosted on the web server side. 现在,您需要为Web服务器端托管的WCF应用程序打开跨域支持。

Web.config Web.config文件

<system.webServer>
<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*"/>
    <add name="Access-Control-Allow-Headers" value="content-type" />
    <add name="Access-Control-Allow-Methods" value="GET,POST,PUT,DELETE,OPTIONS" />
  </customHeaders>
</httpProtocol>

Global.asax Global.asax中

protected void Application_BeginRequest(object sender, EventArgs e)
    {
        if (Request.Headers.AllKeys.Contains("Origin")&&Request.HttpMethod=="OPTIONS")
        {
            Response.End();
        }
    }

Feel free to contact me if you have any questions. 如有任何疑问,请随时与我联系。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM