从jQuery AJAX调用WCF服务方法返回404

时间:2016-05-20 13:04:44

标签: c# jquery .net wcf

这是我的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的新手。

1 个答案:

答案 0 :(得分:0)

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

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

请注意,您正在使用波浪号(〜)字符开始URL。代字号是一个ASP.NET令牌,意思是“应用程序根”。 JQuery不知道这意味着什么,所以ajax调用会像“http://mysite/~/DemoService1.svc/IsEmailAvailable”那样可能不是一个有效的URL。

url参数替换为有效的网址,404可能会消失。用于解决此问题的好工具是浏览器或Fiddler中的开发人员控制台。我发现在解决为什么客户端调用无法正常工作时这两个都非常宝贵(相信我......你将处理大量的HTTP响应代码,并且你需要一个允许你查看的工具例外细节)。

相关问题