Search code examples
c#jqueryjsonajaxstringify

400(Bad Request) when a Json object is posted


I am doing a post request for a wcf service email is my object which is having attributes subject and body. When I try to make a ajax call I am getting 400 Bad Request error this is my code below. I don't know how to put a object in stringify function.

{
  "email": {
     "subject": "b",
     "body": "d"
  }
}

 $('#Button1').click(function() {
            var email = {
                subject: $("#Text1").val(),
                body: $("#Text1").val(),

            }

            $.ajax({
                url:"http://localhost:29143/Restwebservice.svc/sendmail",
                type: 'post',
                cache: false,
                contentType: "application/json; charset=utf-8",
                dataType: 'json',

                //data: JSON.stringify(email)
                data: JSON.stringify(email),
                success: function (data) {
                    $('#target').html(data.msg);
                }
            });

Solution

  • You have not shown us sendmail method,however I assume from the data structure of ajax call it should look like this:

    [DataContract]
    public class EmailEntity
    {
        [DataMember]
        public string subject { get; set; }
        [DataMember]
        public string body { get; set; }
    }
    

    Now the sendmail method would look like this

    [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json,
    ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
    public void sendmail(EmailEntity emailentity)
    {
      ............
    }
    

    Note that request type is wrapped so while posting data from ajax you would ideally create a emailentity object first which would work as wrapper object.

    var emailentity = {};
    emailentity.subject = "Test subject";
    emailentity.body = "Test body";
    
    var jsonObj = JSON.stringify(emailentity);
    var dataToSend = '{"emailentity":'+jsonObj+'}';
    

    this dataToSend will be posted now via ajax.

    $.ajax({
                type: "POST",
                async: false,
                data: dataToSend,
                url: "../path/myService.svc/sendmail",
                contentType: "application/json; charset=utf-8",
                dataType: "json",          
                success: function () {
                    alert("success");
                },
                error: function () {
                    alert("Error");
                }
            });
    

    Hope this helps.