Question

I am trying to access wcf service hosted on IIS from html page using jquery ajax call,I am not able to hit the service , Its throwing 404 not found error, Can i please know should i make changes in the jquery ajax call or web config file to access the service hosted in IIS or some other remote machine

HTML Page:

<!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 Service :

namespace WcfService1
{

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

        }
    }
}

Interface : IService1.cs

namespace WcfService1
{
    [ServiceContract]
    public interface IService1
    {

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

    }

}

WebConfig File:

 <?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>
Was it helpful?

Solution

Here is the another way to go around:

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

And User is your custom class holding detail.

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

   // Remaining attributes here.
}

I don't have much experience with AJAX but I think it should work.

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

OTHER TIPS

Change your OperationContract,

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

All seems well, Need to check services is not giving 404 not found on browser. If you get 404, you need to install "HTTP-Activation" features under "WCF services" on Windows server 8 or 12.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top