none
My wcf rest service cannot visited by Jquery and ajax? RRS feed

  • Question

  • I have make a wcf rest service. And I can use it normally using the webclient class. But when the js client using the jquery post the data into the wcf, the wcf receives an null object. Who can tell me why? 

    The Interface

     [ServiceContract]
        public interface IService
        {
           
             
            #region CLIENT
    
            [OperationContract]
            [WebGet(UriTemplate = "Client", ResponseFormat = WebMessageFormat.Json)]
            List<CLIENT> GetCollection_Client();
    
            [OperationContract]
            [WebGet(UriTemplate = "Client/{id}", ResponseFormat = WebMessageFormat.Json)]
            CLIENT Get_Client(string id);
    
            [OperationContract]
            [WebInvoke(UriTemplate = "Client", Method = "POST", RequestFormat = WebMessageFormat.Json,
                BodyStyle=WebMessageBodyStyle.WrappedRequest, 
             ResponseFormat = WebMessageFormat.Json)]
            void Create_Client(CLIENT postClient);
    
            [OperationContract]
            [WebInvoke(UriTemplate = "Client/{id}", Method = "DELETE")]
            void Delete_Client(string id);
    
            [OperationContract]
            [WebInvoke(UriTemplate = "Client/{id}", Method = "PUT", RequestFormat = WebMessageFormat.Json)]
            void Update_Client(string  id,CLIENT postClient);
    
            #endregion
    
            #region PROJECT
    
            [OperationContract]
            [WebGet(UriTemplate = "Project/{clientId}", ResponseFormat = WebMessageFormat.Json)]
            List<PROJECT> GetCollection_Project(string clientId);
    
            #endregion
    
        }

    The service class

    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
        [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
        // NOTE: If the service is renamed, remember to update the global.asax.cs file
        public class DataService:IService
        {
           private TSDbContext context;
           
            public DataService()
            {
                context = new TSDbContext();
            }
    
            #region PROJECT
    
            public List<PROJECT> GetCollection_Project(string clientId)
            {
                int id = int.Parse(clientId);
                List<PROJECT> list =  context.Set<PROJECT>().Where(p => p.C_ID == id).ToList();
    
                return list;
            }
    
            #endregion
    
            public List<CLIENT> GetCollection_Client()
            {
                //try
                //{
                  
                    return context.Set<CLIENT>().ToList();
                //}
                //catch (Exception ex)
                //{
                //    throw new WebFaultException<string>(string.Format("There are some errors occur on the server: {0}", ex.Message),
                //        HttpStatusCode.ExpectationFailed);
                //}
            }
    
            public CLIENT Get_Client(string id)
            {
                try
                {
                    int value = Convert.ToInt32(id);
                    var entity = context.CLIENTS.Where(p => p.C_ID == value).First();
                    return entity;
                }
                catch (Exception ex)
                {
                    throw new WebFaultException<string>(string.Format("There are some errors occur on the server: {0}", ex.Message),
                        HttpStatusCode.ExpectationFailed);
                }
            }
    
            public void Create_Client(CLIENT postClient)
            {
                //try
                //{
                    context.Set<CLIENT>().Add(postClient);
                    context.SaveChanges();
                //}
                //catch (Exception ex)
                //{
                   
                //    throw new WebFaultException<string>(string.Format("There are some errors occur on the server: {0}", ex.Message),
                //        HttpStatusCode.ExpectationFailed);
                //}
            }
    
            public void Delete_Client(string id)
            {
                try
                {
                    int value = Convert.ToInt32(id);
                    var entity = context.CLIENTS.Where(p => p.C_ID == value).First();
                    context.CLIENTS.Remove(entity);
                    context.SaveChanges();
                }
                catch (Exception ex)
                {
                    throw new WebFaultException<string>(string.Format("There are some errors occur on the server: {0}", ex.Message),
                        HttpStatusCode.ExpectationFailed); 
                }
            }
    
            public void Update_Client(string id,CLIENT postClient)
            {
                try
                {
                    var set = context.Set<CLIENT>();
                    set.Attach(postClient);
                    context.Entry<CLIENT>(postClient).State = System.Data.EntityState.Modified;
                    context.SaveChanges();
                }
                catch (Exception ex)
                {
                    throw new WebFaultException<string>(string.Format("There are some errors occur on the server: {0}", ex.Message),
                        HttpStatusCode.ExpectationFailed);
                }
            }
        }

    The webconfig 

    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
      <configSections>
        <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
        <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
      </configSections>
      <system.web>
        <compilation debug="true" targetFramework="4.0" />
      </system.web>
      <connectionStrings>
        <add name="TimesheetDB" connectionString="Server=.;database =CFTimeSheet; uid=sa;pwd=123;" providerName="System.Data.SqlClient" />
      </connectionStrings>
      <system.webServer>
        <modules runAllManagedModulesForAllRequests="true">
          <add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
        </modules>
      </system.webServer>
      <system.serviceModel>
        <behaviors>
          <endpointBehaviors>
            <behavior name="enabledWebScrip">
              <enableWebScript />
            </behavior>
          </endpointBehaviors>
        </behaviors>
        <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
        <standardEndpoints>
          <webHttpEndpoint>
            <!-- 
                Configure the WCF REST service base address via the global.asax.cs file and the default endpoint 
                via the attributes on the <standardEndpoint> element below
            -->        
            <standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true"  />
          </webHttpEndpoint>
        </standardEndpoints>
      </system.serviceModel>
      <entityFramework>
        <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
      </entityFramework>
    </configuration>

    The client javascript

    function sendAJAX(url, data, success) {
       
        $.ajax({
            type: "POST",
            contentType: "application/json",
            url: url,
            data: data,
            processData: false,
            success: success,
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert("Error Occured!");
            }
        });
    }
    
    
    function addClick() {
        var myDate = new Date();
       
       
        //    data = { C_ID: "1", C_NAME: "23", C_CREATE: myDate };
        var data = new Object();
        data.C_ID = 1;
        data.C_NAME = "js";
        data.C_CREATE = myDate;
    
        jsonStr = JSON.stringify(data);
        var last = "postClient= " + jsonStr;
        sendAJAX("http://localhost:22055/DataService/Client", jsonStr,
                function (msg) {
                    debugger;
                    var result = JSON.parse(msg);
                    alert("good");
                });
    }

    When I use this jquery request to post data, in the method Create_Client get a null parameter.  Why? What's wrong?


    One day a small demo!

    Friday, January 11, 2013 4:58 AM

All replies

  • I find the reason because 

    BodyStyle=WebMessageBodyStyle.WrappedRequest

    this one. But another error exist . When I use query to  get response, I get this 400 bad request. and the response text is but my webclient class visit normally.  why ? Who can help me ?

    <?xml version="1.0" encoding="utf-8"?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
      <head>
        <title>Request Error</title>
        <style>BODY { color: #000000; background-color: white; font-family: Verdana; margin-left: 0px; margin-top: 0px; } #content { margin-left: 30px; font-size: .70em; padding-bottom: 2em; } A:link { color: #336699; font-weight: bold; text-decoration: underline; } A:visited { color: #6699cc; font-weight: bold; text-decoration: underline; } A:active { color: #336699; font-weight: bold; text-decoration: underline; } .heading1 { background-color: #003366; border-bottom: #336699 6px solid; color: #ffffff; font-family: Tahoma; font-size: 26px; font-weight: normal;margin: 0em 0em 10px -20px; padding-bottom: 8px; padding-left: 30px;padding-top: 16px;} pre { font-size:small; background-color: #e5e5cc; padding: 5px; font-family: Courier New; margin-top: 0px; border: 1px #f0f0e0 solid; white-space: pre-wrap; white-space: -pre-wrap; word-wrap: break-word; } table { border-collapse: collapse; border-spacing: 0px; font-family: Verdana;} table th { border-right: 2px white solid; border-bottom: 2px white solid; font-weight: bold; background-color: #cecf9c;} table td { border-right: 2px white solid; border-bottom: 2px white solid; background-color: #e5e5cc;}</style>
      </head>
      <body>
        <div id="content">
          <p class="heading1">Request Error</p>
          <p xmlns="">The server encountered an error processing the request. Please see the <a rel="help-page" href="http://localhost:22055/DataService/help">service help page</a> for constructing valid requests to the service.</p>
        </div>
      </body>
    </html>


    One day a small demo!

    Friday, January 11, 2013 6:05 AM