开发者

JQuery + WCF + HTTP 404 Error

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.
        de开发者_运维问答bugger;
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


Try adding the following code -

Change your web.config to include the following-

<system.serviceModel>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="false" />
</system.serviceModel>

Then, decorate your MyDemo.svc.cs with the following attribute

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]


This was the first time I tried jQuery/JSON. I thought I could get it working with some samples. But as it turns out, its never that easy to get some code running!

so i did console.log and turned out my msg object was like this [ Object Comment: "My Comment" EvalId: "0" Submitter: "SS" Timesent: "/Date(1298299273798+0530)/"

so instead of msg.EvalId all i had to do was msg[0].EvalId.toString()

Definitely the dreaded "undefined" error was something to crack!!

I will definitely be posting on my blog on this.. but after days of banging my head.. turns out I need to go through some basics first!!

But in this process, learnt some good stuff on fiddler, firebug, Cross-site scripting ..

I'm impressed with jQuery/JSON and planning to deep dive now!!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜