none
error consuming json based restful service using ajax call RRS feed

  • Question

  • Hi Guys

    I have created a simple wcf service and can execute it fine using RestSharp. The error code is Request Error when i write a piece of java script and ajax.

    The WCF data contract is

    namespace DomainObjects
    {
        [DataContract]
        public class User
        {
            [DataMember]
            public string MyName { get; set; }
    
            [DataMember]
            public decimal MyId { get; set; }
    
            [DataMember]
            public string Message { get; set; }
        }
    }

    The operation contract and the implementation is

    namespace MYService
    {
        [ServiceContract]
        public interface IUserService
        {
            [OperationContract]
            User GetUser(string id);
    
            [OperationContract]
            User PostAUser(User u);
        }
    
        // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "UserService" in both code and config file together.
        public class UserService : IUserService
        {
            [WebInvoke(Method = "GET",
                       ResponseFormat = WebMessageFormat.Json,
                       UriTemplate = "user/{id}")]
            public User GetUser(string id)
            {
                User u = new User();
                u.MyId = Convert.ToDecimal(id);
                u.MyName = String.Format("Id:{0}", id);
                u.Message = "The Get is good....";
                return u;
            }
            
            [WebInvoke(Method = "POST",
                       RequestFormat = WebMessageFormat.Json,
                       ResponseFormat = WebMessageFormat.Json,
                       UriTemplate = "auth/")]
            public User PostAUser(User u)
            {
                User uNew = new User();
                uNew.MyName = String.IsNullOrEmpty(u.MyName) ? string.Empty : u.MyName;
                uNew.MyId = u.MyId;
                uNew.Message = "Post is good...";
                return uNew;
            }
        }
    }

    The web config file is

    <?xml version="1.0"?>
    <configuration>
    
      <appSettings>
        <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
      </appSettings>
      <system.web>
        <compilation debug="true" targetFramework="4.5" />
        <httpRuntime targetFramework="4.5"/>
      </system.web>
      <system.serviceModel>
        <services>
          <!-- User Service -->
          <service name="MYService.UserService" behaviorConfiguration="serviceBehavior">
            <endpoint address="" binding="webHttpBinding" contract="MYService.IUserService" behaviorConfiguration="web">
            </endpoint>
          </service>
        </services>
        <behaviors>
          <serviceBehaviors>
            <behavior name="serviceBehavior">
              <serviceMetadata httpGetEnabled="true"/>
              <serviceDebug includeExceptionDetailInFaults="false"/>
            </behavior>
          </serviceBehaviors>
          <endpointBehaviors>
            <behavior name="web">
              <webHttp/>
            </behavior>
          </endpointBehaviors>
        </behaviors>
      </system.serviceModel>  
      <system.webServer>
        <modules runAllManagedModulesForAllRequests="true"/>
        <!--
            To browse web app root directory during debugging, set the value below to true.
            Set to false before deployment to avoid disclosing web app folder information.
          -->
        <directoryBrowse enabled="true"/>
      </system.webServer>
    
    </configuration>


    The Web service svc is hosted in a .net web project running under IIS. I access the service through RestSharp using the URL http://localhost/testapp/Service1.svc" and both Get and Post works like a charm.

    Then i wrote a simple HTML page with 2 buttons (in a separate virtual app - not even a .Net project) having jQuery and java script.

    The Get works fine (Code below)

    function ExecuteGet()
    {
      alert('this is a get');
    
                 $.ajax({
                     type: "GET",
                     url: "http://localhost/testapp/Service1.svc/user/46",
                     contentType: "application/json; charset=utf-8",
                     processData: true,
    dataType: "jsonp",
                     success: function (data, status, jqXHR) {
                         alert("success..." + data);
                     },
                     error: function (xhr) {
                         alert(xhr.responseText);
                     }
                 });
    }


    But the post is an issue giving me a request error (Below)

     
    function ExecuteValidate()
    {
    alert('this is a post');
    
    var authdata =  {"MyName":"","MyId":100.0,"Message":""};
    
    $.ajax({
                     type: "POST",
                     url: "http://localhost/testapp/Service1.svc/auth",
                     data: JSON.stringify(authdata),
                     contentType: "application/json; charset=utf-8",
                     dataType: "jsonp",
                     processData: true,
                     success: function (data, status, jqXHR) {
                         alert("success..." + data);
                     },
                     error: function (xhr) {
                         alert(xhr.responseText);
                     }
                 });
    }


    Any clues



    Wednesday, November 12, 2014 8:42 PM

Answers

  • Hi Siddharth Kumar,

    >>But the post is an issue giving me a request error (Below)

    Please try to modify your post method as following:

    function ExecuteValidate() {
                alert('this is a post');
                $.ajax({
                    type: "POST",
                    url: "http://localhost/testapp/Service1.svc/auth/",
                    data: '{ "MyName": "", "MyId": 100.0, "Message": "" }',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    processData: true,
                    success: function (data, status, jqXHR) {
                        alert("success..." + JSON.stringify(data));
                    },
                    error: function (xhr) {
                        alert(xhr.responseText);
                    }
                });
    
            }

    Then the result:

    Best Regards,
    Amy Peng


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Thursday, November 20, 2014 9:52 AM
    Moderator

All replies

  • what error do you meet?
    Thursday, November 13, 2014 10:12 AM
  • Hi Siddharth Kumar,

    >>But the post is an issue giving me a request error (Below)

    Please try to modify your post method as following:

    function ExecuteValidate() {
                alert('this is a post');
                $.ajax({
                    type: "POST",
                    url: "http://localhost/testapp/Service1.svc/auth/",
                    data: '{ "MyName": "", "MyId": 100.0, "Message": "" }',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    processData: true,
                    success: function (data, status, jqXHR) {
                        alert("success..." + JSON.stringify(data));
                    },
                    error: function (xhr) {
                        alert(xhr.responseText);
                    }
                });
    
            }

    Then the result:

    Best Regards,
    Amy Peng


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Thursday, November 20, 2014 9:52 AM
    Moderator