none
C# Json 400 Bad Request RRS feed

  • Question

  • I have been trying to get this to work for the last couple of days, I have a metro app that needs to get and post json data to a wcf service. The getting the json data from wcf was easy enough however I have encountered 400 Bad Request error when I try to post parsed json data. Below is my code, hopefully someone has had this problem and can help me out.

    Service1.svc.cs

    public string InsertSale(string saleDetails)
            {
                return "";
            }


    IService.cs

    [WebInvoke(Method = "POST", UriTemplate = "SubmitSale", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
    [OperationContract]
    string InsertSale(string saleDetails);


    MainPage.xaml.cs

    private async void PostToJsonServer(SalesDetails sd) { string postBody = JsonConvert.SerializeObject(sd);

    //below is a sample of postBody after Serialization HttpClient client = new HttpClient(); HttpContent content = new StringContent(postBody, Encoding.UTF8, "application/json"); Uri postUrl = new Uri("http://localhost:1325/Service1.svc/JSONService/SubmitSale", UriKind.Absolute); content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage wcfResponse = await client.PostAsync(postUrl, content); MessageDialog md = new MessageDialog(wcfResponse.ToString() + "\r\n\r\n\r\n" + wcfResponse.Content.ToString(), "MESSGAE"); md.ShowAsync(); }


    SalesDetails Data Contract

    [DataContract]
        public class SalesDetails
        {
            string saleID = string.Empty;
            string saleType = string.Empty;
            double saleTotal = 0.0;
            double saleTax = 0.0;
            string saleStatus = string.Empty;
            int storeID = 0;
            DateTime dateTime = DateTime.Now;
            List<SalesProductDetails> saleProducts = null;
            List<SalesPaymentDetails> payment = null;
    
            [DataMember]
            public string SaleID
            {
                get { return saleID; }
                set { saleID = value; }
            }
    
            [DataMember]
            public string SaleType
            {
                get { return saleType; }
                set { saleType = value; }
            }
    
            [DataMember]
            public double SaleTotal
            {
                get { return saleTotal; }
                set { saleTotal = value; }
            }
    
            [DataMember]
            public double SaleTax
            {
                get { return saleTax; }
                set { saleTax = value; }
            }
    
            [DataMember]
            public string SaleStatus
            {
                get { return saleStatus; }
                set { saleStatus = value; }
            }
    
            [DataMember]
            public string Username
            {
                get;
                set;
            }
    
            [DataMember]
            public int StoreInformation
            {
                get { return storeID; }
                set { storeID = value; }
            }
    
            [DataMember]
            public int CustomerID
            {
                get;
                set;
            }
    
            [DataMember]
            public int NumberOfCustomers
            {
                get;
                set;
            }
    
            [DataMember]
            public List<SalesProductDetails> Products
            {
                get { return saleProducts; }
                set { saleProducts = value; }
            }
    
            [DataMember]
            public List<SalesPaymentDetails> Payments
            {
                get { return payment; }
                set { payment = value; }
            }
    
            [DataMember]
            public DateTime DateTime
            {
                get { return dateTime; }
                set { dateTime = value; }
            }
        }


    postBody Serialization example

    {"SaleID":"","SaleType":"SAL","SaleTotal":9.0,"SaleTax":0.81818181818181812,"SaleStatus":"Paid","Username":"ben.ringrose","StoreInformation":1,"CustomerID":0,"NumberOfCustomers":1,"Products":[{"SaleID":"","SaleDetailsID":0,"ProductPrice":2.5,"ProductQty":1.0,"TaxAmount":0.22727272727272727,"ProductCode":"2182","ProductDescription":"TEA SMALL"},{"SaleID":"","SaleDetailsID":0,"ProductPrice":3.0,"ProductQty":1.0,"TaxAmount":0.27272727272727271,"ProductCode":"2183","ProductDescription":"TEA MEDIUM"},{"SaleID":"","SaleDetailsID":0,"ProductPrice":3.5,"ProductQty":1.0,"TaxAmount":0.31818181818181818,"ProductCode":"2184","ProductDescription":"TEA LARGE"}],"Payments":[{"SaleID":"","SalePaymentID":0,"PaymentName":"Cash","PaymentAmount":9.0}],"DateTime":"2015-05-06T11:26:07.2824181+10:00"}

    Entire web.config file

    <?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>
        <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
    
        <services>
          <service behaviorConfiguration="Default" name="WcfServiceTestingAndTagging.Service1">
            <!--<host>
              <baseAddresses>
                <add baseAddress = "http://10.18.4.200:8733/Service1/" />
                <add baseAddress = "http://10.18.4.200/CafePOS/" />
                <add baseAddress = "http://localhost:8733/Design_Time_Addresses/WcfServiceLibrary1/Service1/" />
              </baseAddresses>
            </host>-->
    
            <endpoint address="" binding="basicHttpBinding" contract="WcfServiceTestingAndTagging.IService1" />
            <endpoint address="JSONService" behaviorConfiguration="webBehavior" binding="webHttpBinding" contract="WcfServiceTestingAndTagging.IService1" />
            <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
          </service>
        </services>
        
        <client>
          <endpoint address="" behaviorConfiguration="webBehavior" binding="webHttpBinding" contract="WcfServiceTestingAndTagging.IService1" />
          <endpoint address="basic" binding="basicHttpBinding" contract="WcfServiceTestingAndTagging.IService1" />
          <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
        </client>
        
        <bindings>
          <basicHttpBinding>
            <binding name="BasicBinding" maxReceivedMessageSize="2000000" maxBufferSize="2000000" transferMode="Streamed">
              <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647" />
            </binding>
          </basicHttpBinding>
        </bindings>
    
        <behaviors>
          <endpointBehaviors>
            <behavior name="webBehavior">
              <webHttp helpEnabled="true"/>
              <dataContractSerializer maxItemsInObjectGraph="100000000"/>
            </behavior>
          </endpointBehaviors>
          <serviceBehaviors>
            <behavior name="Default">
              <serviceMetadata httpGetEnabled="true" httpsGetEnabled="True" />
              <serviceDebug includeExceptionDetailInFaults="false"/>
            </behavior>
            <behavior name="">
              <serviceMetadata httpGetEnabled="True" httpsGetEnabled="True"/>
              <serviceDebug includeExceptionDetailInFaults="False" />
            </behavior>
          </serviceBehaviors>
        </behaviors>
        
        <protocolMapping>
          <add binding="basicHttpsBinding" scheme="https" />
        </protocolMapping>
        
      </system.serviceModel>
      
      <system.webServer>
        <modules runAllManagedModulesForAllRequests="true"/>
        <directoryBrowse enabled="true"/>
      </system.webServer>
    
    </configuration>

    If you need any other code please let me know and I will supply

    Again I hope someone can help

    Cheers,
    Ben

    Wednesday, May 6, 2015 12:28 AM

Answers

  • Hi BR Computing,

    I have tested your code and I can reproduce your issue, by default in your service it will use Bare BodyStyle, please use the Wrapped for instead:

    [WebInvoke(Method = "POST", UriTemplate = "SubmitSale", BodyStyle = WebMessageBodyStyle.Wrapped,ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
    [OperationContract]
    string InsertSale(string saleDetails);
    After that, it works well in my side.
    For more information, please try to refer to:
    #Difference between WebMessageBodyStyle.Wrapped and WebMessageBodyStyle.Bare:
    http://www.wcf.dotnetarchives.com/2013/12/difference-between-webmessagebodystylew.html .

    Besides, I found that you have used the SalesDetails object as paramenter, but in your method its parameter is string, so the other way for your question is to modify your InsertSale method as following:

    [WebInvoke(Method = "POST", UriTemplate = "SubmitSale", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
    [OperationContract]
    string InsertSale(SalesDetails saleDetails);

    For more information, please try to check the following sample about how to use HttpClient to post Json data to WCF Services in Windows Store apps:
    https://code.msdn.microsoft.com/windowsapps/How-to-use-HttpClient-to-b9289836 .

    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.




    Wednesday, May 6, 2015 6:49 AM
    Moderator