从Jquery ajax调用WCF服务时出现404 Not Found错误

时间:2014-03-25 05:36:07

标签: jquery web-services wcf wcf-data-services

我正在尝试使用jquery ajax调用从html页面访问IIS上托管的wcf服务,我无法点击该服务,它抛出404找不到错误,我能否知道我应该在中进行更改jquery ajax调用 web配置文件以访问IIS或其他远程计算机中托管的服务

HTML页面:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <script src="http://code.jquery.com/jquery-latest.js"></script>
    <script src="json.js"></script>
    <title></title>
    <script type="text/javascript">
        var inputdata = { "userId": "101"};
        jQuery.support.cors = true;
        $.ajax({
            url: 'http://<ipaddress>/WcfService1/Service1.svc/GetUserDetails',
            data: JSON.stringify(inputdata),
            type: 'POST',
            dataType : "jsonp",
            contentType: "application/json; charset=utf-8",
            //jsonpCallback: "handleResponse",
            success: function (result) {
                console.log(result.data);
                alert("success");
            },
            error: function (request, error) {
                alert('Network error has occurred please try again.Please check your connection and try again.');
                return;}
});
</script>
   </head>
<body>
</body>
</html>

Wcf服务:

namespace WcfService1
{

    [ServiceBehavior(AddressFilterMode = AddressFilterMode.Any)]
    public class Service1 : IService1
    {
      public string GetUserDetails(string userId)
        {
           // Returns User Details 

        }
    }
}

接口:IService1.cs

namespace WcfService1
{
    [ServiceContract]
    public interface IService1
    {

        [OperationContract]
        [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json)]
         int GetUserDetails(string strUserID);

    }

}

WebConfig文件:

 <?xml version="1.0"?>
    <configuration>

      <system.web>
        <compilation debug="true" targetFramework="4.5" />
        <httpRuntime targetFramework="4.5"/>
      </system.web>
      <system.serviceModel>
        <behaviors>
          <serviceBehaviors>
            <behavior name="ServiceBehavior">
              <serviceMetadata httpGetEnabled="true"/>
              <serviceDebug includeExceptionDetailInFaults="true"/>
            </behavior>
          </serviceBehaviors>
          <endpointBehaviors>
            <behavior name="EndpBehavior">
              <enableWebScript/>
            </behavior>
          </endpointBehaviors>
        </behaviors>
        <services>
          <service behaviorConfiguration="ServiceBehavior" name="WcfService1.Service1">
            <endpoint address="" binding="webHttpBinding" contract="WcfService1.IService1" behaviorConfiguration="EndpBehavior" bindingConfiguration="crossdomain"/>
            <host>
              <baseAddresses>
                <add baseAddress="http://localhost/WcfService1/Service1.svc"/>
              </baseAddresses>
            </host>
          </service>
        </services>
        <!--<protocolMapping>
            <add binding="basicHttpsBinding" scheme="https" />
        </protocolMapping>-->
        <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" >

        </serviceHostingEnvironment>
        <bindings>
          <webHttpBinding>
            <binding name="crossdomain" crossDomainScriptAccessEnabled="true"/>
          </webHttpBinding>
        </bindings>
      </system.serviceModel>
      <system.webServer>
        <modules runAllManagedModulesForAllRequests="true"/>

        <directoryBrowse enabled="true"/>
        <httpProtocol>
    <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Headers" value="Content-Type, Accept" />
    <add name="Access-Control-Allow-Methods" value="POST,GET,OPTIONS" />
    <add name="Access-Control-Max-Age" value="1728000" />
    </customHeaders>
    </httpProtocol>
      </system.webServer>

    </configuration>

3 个答案:

答案 0 :(得分:1)

更改您的OperationContract,

    [OperationContract]
    [WebInvoke(UriTemplate = "/GetUserDetails", 
    RequestFormat= WebMessageFormat.Json,   
    ResponseFormat = WebMessageFormat.Json, Method = "POST")] 
    int GetUserDetails(string strUserID);

答案 1 :(得分:1)

这是另一种方法:

[OperationContract]
[WebGet(UriTemplate = "/GetUserDetails/{strUserID}", 
ResponseFormat = WebMessageFormat.Json)] 
User GetUserDetails(string strUserID);

User是您的自定义类,包含详细信息。

[DataContract]
public class User
{
   [DataMemeber]
   public in UserID {get; set;}

   // Remaining attributes here.
}

我对AJAX没有多少经验,但我认为它应该有用。

url: 'http://<ipaddress>/WcfService1/Service1.svc/GetUserDetails/101'
type: 'GET',
//contentType: "application/json; charset=utf-8", No need to mention it for GET

答案 2 :(得分:0)

一切似乎都很好, 需要检查服务是不是在浏览器上找不到404。 如果获得404,则需要在Windows服务器8或12上的“WCF服务”下使用install "HTTP-Activation"个功能。