JQuery + WCF + HTTP 404 Error

Posted by hangar18 on Programmers See other posts from Programmers or by hangar18
Published on 2011-02-12T14:07:43Z Indexed on 2011/02/12 15:32 UTC
Read the original article Hit count: 401

Filed under:
|

HI All, I've searched high and low and finally decided to post a query here.

I'm writing a very basic HTML page from which I'm trying to call a WCF service using jQuery and parse it using JSON.

Service:

IMyDemo.cs

[ServiceContract]
    public interface IMyDemo
    {
        [WebInvoke(Method = "POST",
            BodyStyle = WebMessageBodyStyle.WrappedRequest,
            ResponseFormat = WebMessageFormat.Json)]
         Employee DoWork();


        [OperationContract]
        [WebInvoke(Method = "POST",
            BodyStyle = WebMessageBodyStyle.WrappedRequest,
            ResponseFormat = WebMessageFormat.Json)]
         Employee GetEmp(int age, string name);


    }

    [DataContract]
    public class Employee
    {
        [DataMember]
        public int EmpId { get; set; }

        [DataMember]
        public string EmpName { get; set; }

        [DataMember]
        public int EmpSalary { get; set; }

    }

MyDemo.svc.cs

 public Employee DoWork()
        {
            // Add your operation implementation here 
            Employee obj = new Employee() { EmpSalary = 12, EmpName = "SomeName" };
            return obj;
        }

 public Employee GetEmp(int age, string name)
        {
            Employee emp = new Employee();

            if (age > 0)
                emp.EmpSalary = 12 + age;

            if (!string.IsNullOrEmpty(name))
                emp.EmpName = "Server" + name;

            return emp;
        }

WEb.Config

<system.serviceModel>
    <services>
      <service behaviorConfiguration="EmployeesBehavior" name="MySample.MyDemo">
        <endpoint address="" binding="webHttpBinding" contract="MySample.IMyDemo" behaviorConfiguration="EmployeesBehavior"/>
      </service>

    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="EmployeesBehavior">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="EmployeesBehavior">
          <webHttp/>         
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>

MyDemo.htm

<head>
    <title></title>
    <script type="text/javascript" language="javascript" src="Scripts/jquery-1.4.1.js"></script>
    <script type="text/javascript" language="javascript" src="Scripts/json.js"></script>
    <script type="text/javascript">
        //create a global javascript object for the AJAX defaults.
        debugger;
var ajaxDefaults = {};

ajaxDefaults.base = { 
    type: "POST", 
    timeout : 1000,

    dataFilter: function (data) { 
        //see http://encosia.com/2009/06/29/never-worry-about-asp-net-ajaxs-d-again/ 
        data = JSON.parse(data); //use the JSON2 library if you aren’t using FF3+, IE8, Safari 3/Google Chrome 
        return data.hasOwnProperty("d") ? data.d : data; 
    },

    error: function (xhr) { 
        //see 
        if (!xhr) return; 
        if (xhr.responseText) { 
            var response = JSON.parse(xhr.responseText); 
            //console.log works in FF + Firebug only, replace this code 
            if (response)    alert(response); 
            else alert("Unknown server error"); 
        } 
    } 
};

ajaxDefaults.json = $.extend(ajaxDefaults.base, { 
    //see http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/ 
    contentType: "application/json; charset=utf-8", 
    dataType: "json" 
});

var ops = {
    baseUrl: "/MyService/MySample/MyDemo.svc/",

    doWork: function () { 
        //see http://api.jquery.com/jQuery.extend/ 
        var ajaxOptions = $.extend(ajaxDefaults.json, {

            url: ops.baseUrl + "DoWork", 
            data: "{}",

            success: function (msg) { 
                console.log("success"); 
                console.log(typeof msg); 
                if (typeof msg !== "undefined") { 
                    console.log(msg); 
                } 
            } 
        });

        $.ajax(ajaxOptions); 
        return false; 
    },
    getEmp: function () { 
        var ajaxOpts = $.extend(ajaxDefaults.json, {

            url: ops.baseUrl + "GetEmp", 
            data: JSON.stringify({ age: 12, name: "NameName" }),

            success: function (msg) { 
                $("span#lbl").html("age: " + msg.Age + "name:" + msg.Name); 
            } 
        });

        $.ajax(ajaxOpts); 
        return false; 
    } 
}
    </script>

</head>
<body>
<span id="lbl">abc</span> 
<br /><br />
<input type="button" value="GetEmployee" id="btnGetEmployee" onclick="javascript:ops.getEmp();" /> 
</body>

I'm just not able to get this running. When I debug, I see the error being returned from the call is "

Server Error in '/jQuerySample' Application.

        <h2> <i>HTTP Error 404 - Not Found.</i> </h2></span>

"

Looks like I'm missing something basic here. My sample is based on this

I've been trying to fix the code for sometime now so I'd like you to take a look and see if you can figure out what is it that I'm doing wrong here.

I'm able to see that the service is created when I browse the service in IE. I've also tried changing the setting as mentioned here

Appreciate your help. I'm gonna blog about this as soon as the issue is resolved for the benefit of other devs Thanks -Soni

© Programmers or respective owner

Related posts about jQuery

Related posts about wcf