Abhishek Mathur
Abhishek Mathur

Reputation: 316

WCF is giving an error of 400 Bad Request in Post Method

I have this WCF Service:

IService.cs:

public interface IService
{
   [OperationContract]
   [WebInvoke(Method = "POST", UriTemplate = "/PostComments", BodyStyle = WebMessageBodyStyle.Wrapped,
    RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
   string PostComments(PostComment comment);

 [DataContract]
public class PostComment
{
    private string Id;
    private string FullName;
    private string Email;
    private string Location;
    private string Comments;
    private string Type;

    [DataMember]
    public string id { get { return Id; } set { Id = value; } }
    [DataMember]
    public string fullname { get { return FullName; } set { FullName = value; } }
    [DataMember]
    public string email { get { return Email; } set { Email = value; } }
    [DataMember]
    public string location { get { return Location; } set { Location = value; } }
    [DataMember]
    public string comments { get { return Comments; } set { Comments = value; } }
    [DataMember]
    public string type { get { return Type; } set { Type = value; } }
}

Service.svc.cs:

public string PostComments(PostComment commnt)
        {
            int ItemId;
            string Comments, FullName, Location, Email, Type;

            ItemId = Convert.ToInt32(commnt.id);
            Type = commnt.type;
            Comments = commnt.comments;
            FullName = commnt.fullname;
            Location = commnt.location;
            Email = commnt.email;
            int i = 0;

            if (Type == "Style")
            {
                adp = new SqlDataAdapter("insert into tblComment(intId,strComments,strFullName,strLocation,strEmail,dtPosted,blnApprove) values("+ItemId+",'"+Comments+"','"+FullName+"','"+Location+"','"+Email+"',GetDate(),1)", offcon);
                adp.Fill(ds1,"StComment");
                DataTable dt = ds1.Tables["StComment"];
                i++;
            }
            else if (Type == "Article")
            {
                adp = new SqlDataAdapter("insert into tblNewsComment(intArticleId,strComments,strFullName,strLocation,strEmail,dtPosted,blnApprove) values(" + ItemId + ",'" + Comments + "','" + FullName + "','" + Location + "','" + Email + "',GetDate(),1)", offcon);
                adp.Fill(ds1, "ArtComment");
                DataTable dt = ds1.Tables["ArtComment"];
                i++;
            }
            if (i > 0)
            {
                return "Comment Successfully Submitted.";
            }
            else
            {
                return "Comment falied to Submit.";
            }
        }

web.config file:

<?xml version="1.0"?>
<configuration>
<connectionStrings>
  <add name="con" connectionString="Data Source=.;Initial Catalog=PatrikaData;Integrated Security=SSPI;"/>  
</connectionStrings>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
    <httpRuntime requestPathInvalidCharacters="&lt;,&gt;,*,%,:,\"/>
  </system.web>
  <system.serviceModel>
    <services>
      <service behaviorConfiguration="ServiceBehaviour" name="WcfService.Service">
        <endpoint address="" behaviorConfiguration="web" binding="webHttpBinding"
          contract="WcfService.IService" />
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="ServiceBehaviour">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="web">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <serviceHostingEnvironment/>
    <bindings>
      <webHttpBinding>
        <binding name="web"
                 maxBufferPoolSize="1500000"
                 maxReceivedMessageSize="1500000"
                 maxBufferSize="1500000">
          <readerQuotas
                maxArrayLength="656000"
                maxBytesPerRead="656000"
                maxDepth="32"
                maxNameTableCharCount="656000"
                maxStringContentLength="656000"
            />
        </binding>
      </webHttpBinding>
    </bindings>
  </system.serviceModel>  
</configuration>

Now if I am working with BasicHttpBinding and testing with the WCF test client then everything is working fine.

But when I work with WebHttpBinding and testing with Google's Advanced Rest Client and posting data through that then I am getting this error:

The server encountered an error processing the request. The exception message is 'The formatter threw an exception while trying to deserialize the message: Error in deserializing body of request message for operation 'PostComments'. Encountered unexpected character 'T'.'. See server logs for more details. The exception stack trace is:

at System.ServiceModel.Dispatcher.OperationFormatter.DeserializeRequest(Message message, Object[] parameters) at System.ServiceModel.Dispatcher.DemultiplexingDispatchMessageFormatter.DeserializeRequest(Message message, Object[] parameters) at System.ServiceModel.Dispatcher.UriTemplateDispatchFormatter.DeserializeRequest(Message message, Object[] parameters) at System.ServiceModel.Dispatcher.CompositeDispatchFormatter.DeserializeRequest(Message message, Object[] parameters) at System.ServiceModel.Dispatcher.DispatchOperationRuntime.DeserializeInputs(MessageRpc& rpc) at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage41(MessageRpc& rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc& rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(MessageRpc& rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage3(MessageRpc& rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage2(MessageRpc& rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage11(MessageRpc& rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage1(MessageRpc& rpc) at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)

And Sometime this:

The server encountered an error processing the request. The exception message is 'Error in deserializing body of request message for operation 'PostComments'. OperationFormatter encountered an invalid Message body. Expected to find an attribute with name 'type' and value 'object'. Found value 'number'.'. See server logs for more details. The exception stack trace is:

at System.ServiceModel.Dispatcher.OperationFormatter.DeserializeRequest(Message message, Object[] parameters) at System.ServiceModel.Dispatcher.DemultiplexingDispatchMessageFormatter.DeserializeRequest(Message message, Object[] parameters) at System.ServiceModel.Dispatcher.UriTemplateDispatchFormatter.DeserializeRequest(Message message, Object[] parameters) at System.ServiceModel.Dispatcher.DispatchOperationRuntime.DeserializeInputs(MessageRpc& rpc) at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(MessageRpc& rpc) at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)

I really don't know where I am wrong as this service was working fine yesterday on the same rest client of google. I have to deploy this service on the server ASAP. Please Help!!!!

[UPDATE]

Fiddler's Output:

HTTP/1.1 400 Bad Request

Server: ASP.NET Development Server/10.0.0.0
Date: Thu, 27 Sep 2012 10:33:24 GMT
X-AspNet-Version: 4.0.30319
Content-Length: 3513
Cache-Control: private
Content-Type: text/html
Connection: Close

Raw Body which Google is sending:

{
    "Id": "818744",
    "FullName": "Abhishek",
    "Email": "[email protected]",
    "Location": "Jaipur",
    "Comments": "asdkjfjk sdnfjlksdjlk dfljkfsd",
    "Type": "Style"
}

[UPDATE 2] I have gone through Service Tracker then i found that the root value which i am getting having Number and the service is expecting Object. so if it will trigger something as i am totally blank now...

Upvotes: 3

Views: 4180

Answers (1)

James Ralston
James Ralston

Reputation: 1208

Your json that is being posted has all of they keys starting with capital letters, your public properties (which are marked with the lower case attribute) start with lowercase letters. You should have them match or add use [Datamember(name="key")] to ensure they are mapping properly.

Upvotes: 1

Related Questions