【问题标题】:Calling WCF service method from jQuery AJAX returns 404从 jQuery AJAX 调用 WCF 服务方法返回 404
【发布时间】:2016-09-17 18:24:28
【问题描述】:

这是我的 jQuery AJAX 方法:

$(document).ready(function() {  
    $("#btnSubmit").click(function() {
        alert("Test");
        var param = $("#txtEmail").val();
        $.ajax({
            url:"~/DemoService1.svc/IsEmailAvailable",
            type: "POST", 
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            //data: JSON.stringify({ Email: $('#txtEmail').val() }),
            data: param,
            success: function(msg) { //On Successfull service call
                ServiceSucceeded(msg);
            },
            error: ServiceFailed    
        });
    });

    function ServiceFailed(result) {
        alert('Service call failed: ' + result.status + ' ' + result.statusText);
        Type = null;
        varUrl = null;
        Data = null; 
        ContentType = null;
        DataType = null;
        ProcessData = null;
    }
});

这是我的服务接口。

[OperationContract]
[WebInvoke(UriTemplate = "/IsEmailAvailable", Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
bool IsEmailAvailable(string Email);

我的 webconfig 是这样的:

<client>
    <endpoint address="http://localhost:56537/DemoService1.svc" binding="basicHttpBinding"
    bindingConfiguration="BasicHttpBinding_IDemoService1" contract="DemoService.IDemoService1"
    name="BasicHttpBinding_IDemoService1" />
</client>
<behaviors>
    <serviceBehaviors>
        <behavior name="ServiceBehaviour">
            <serviceMetadata httpGetEnabled="true" />
            <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
    </serviceBehaviors>
    <endpointBehaviors>
         <behavior name="EndBehaviour">
             <webHttp/>
         </behavior>
    </endpointBehaviors>
</behaviors>
<services>
      <service behaviorConfiguration="ServiceBehaviour" name="DemoService">
          <endpoint address="" binding="webHttpBinding" contract="IDemoService1" behaviorConfiguration="EndBehaviour"></endpoint>
      </service>
  </services>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />

请提供解决方案。我是 jQuery 新手。

【问题讨论】:

    标签: c# jquery .net wcf


    【解决方案1】:

    看起来问题出在您的 AJAX 调用中的 URL:

    url:"~/DemoService1.svc/IsEmailAvailable",
    

    请注意,URL 以波浪号 (~) 字符开头。波浪号是一个 ASP.NET 标记,意思是“应用程序根”。 JQuery 不知道这意味着什么,因此 ajax 调用将转到类似“http://mysite/~/DemoService1.svc/IsEmailAvailable”的内容,这可能不是有效的 URL。

    用有效的 URL 替换 url 参数,404 可能会消失。解决此问题的好工具是浏览器或 Fiddler 中的开发人员控制台。在排除客户端调用无法正常工作的原因时,我发现两者都是非常宝贵的(相信我……您将要处理大量 HTTP 响应代码,并且您需要一个允许您查看的工具异常详情)。

    【讨论】:

      猜你喜欢
      • 2011-01-04
      • 1970-01-01
      • 2011-03-04
      • 2012-03-05
      • 2016-09-20
      • 2011-09-25
      • 1970-01-01
      • 2020-12-02
      • 1970-01-01
      相关资源
      最近更新 更多