WCF: Why do I keep getting a 400 Bad Request Error? - c#

I'm trying to invoke a WCF service method using POST and sending data encoded as json but no matter what I keep getting a bad request error.
This is my method signature:
[WebInvoke(Method = "POST",
RequestFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.WrappedRequest)]
public int Publish(List<MeasurementData> data)
This is my MeasurementData model definition:
[DataContract]
public class MeasurementData
{
[DataMember]
public string ReadingDate;
[DataMember]
public int Unit { get; set; }
[DataMember]
public string ParameterAbbreviation { get; set; }
[DataMember]
public decimal Measurement { get; set; }
}
And this is how I'm calling it from the client:
var data = '[{"Measurement": 12678967.543233, "ParameterAbbreviation": "String content", "ReadingDate": "String content","Unit": 2147483647}]';
$.ajax({
type: "POST",
url: "/SiennaAddMeasurement/Publish",
data: "{ 'data' : '" + data + "' }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
}
});
Is there something I'm missing?

you can check this below post.
400 Bad Request HTTP Response using a WCF POST via JQuery
some one has already faced such an error it turned to be an error related to the parameters pass.
hope it can help

Related

get "Request Payload" in asp.net core controller

on the client side, I do
$.ajax({
url: '/emplacements/keyexist',
type: "POST",
data: JSON.stringify(postData),
dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
However the values in the action method are always 'null'
[AcceptVerbs("GET", "POST")]
public IActionResult KeyExist(
string nom, //[Bind(Prefix = nameof(EmplacementDTO.Nom))],
int id //[Bind(Prefix = nameof(EmplacementDTO.Id))]
)
{
// nom == null
// id == 0
how to fix it?
first make a model for your payload like below.
public class MyPayload
{
public string Nom{ get; set; }
public int Id { get; set; }
}
and inside your controller Action method
public IActionResult KeyExist([FromBody] MyPayload payload)
[FromBody] will automatically map the request body if property names are matched.
and your ajax call has another issue that you sending the Id as string but the Controller expect an int

Sending JSON from AJAX to Controller Class

I am trying to send JSON to a class and it seems straightforward but for some reason it always shows up as null? Here's the situation:
AjaxCall is triggered by a change event. The url is correct, type is set to POST, and data is already converted with JSON.stringify() and logs as {"country":"Canada"}
function AjaxCall(u, d, t){
console.log(d);
return $.ajax({
url: u,
type: t ? t : 'GET',
data: d,
dataType: 'json',
contentType: 'application/json'
});
}
The class is triggered, but the country string is always null.
[HttpPost]
public JsonResult GetProv(string country)
{
//do whatever
}
What am I missing?!
Edit:
My Model:
public class country
{
public int Id { get; set; }
public string Name { get; set; }
}

Asp.Net how to retrieve JSON from jQuery

I have created a JSON in jQuery which looks like this:
{
"objects":[
{
"ObjectId":1,
"Line1":"Software",
"Line2":"Microsoft",
"Line3":"Web",
"Line4":"Asp.Net",
"Line5":"jQuery"
},
{
"ObjectId":2,
"Line1":"Hardware",
"Line2":"Microsoft",
"Line3":"Computer",
"Line4":"Surface",
"Line5":"Pro"
}
]
}
Now I use AJAX to send it via jQuery to my controller:
var postData = { objects: objectArray };
// Fire off the request to controller
$.ajax({
cache: false,
url: '/Controller/myAction',
type: "POST",
dataType: 'html',
data: postData,
success: function (result) {
// success handler
}
})
public ActionResult myAction(???)
{
return view();
}
What I am not sure about is how I receive the object in my controller. Can someone help me with this please.
Thanks in advance!
Just a little lifehack for future: if you have to add new class based on existing JSON or XML model, there are awesome built-in tool in Visual Studio:
Class generating from JSON/XML models
This should work, start by creating a model object to represent the data on the server side
public class ObjectModel
{
public string ObjectId { get; set; }
public string Line1 { get; set; }
public string Line2 { get; set; }
public string Line3 { get; set; }
public string Line4 { get; set; }
public string Line5 { get; set; }
}
Then define your mvc actions parameter like this
[HttpPost]
public ActionResult myAction(List<ObjectModel> objects)
{
return view();
}
then simply pass the object array as json
// Fire off the request to controller
$.ajax({
cache: false,
url: '/Controller/myAction',
type: "POST",
contentType: "application/json",
dataType: 'json',
data: JSON.stringify(objectArray),
success: function (result) {
// success handler
}
})

JsonConvert.DeserializeObject<T>(value) does not deserialize the object assigned

I have created a page with a KnockoutJS viewmodel. I want to post the Data to my Server using Web API.
I use this AJAX post:
$.ajax({
url: "/api/blogpost",
contenttype: "application/x-www-form-urlencoded",
data: '=' + encodeURIComponent(ko.toJSON(self.Blog)),
type: "POST",
dataType: "JSON",
timeout: 10000,
success: function (Result) {
},
error: function (xhr, status) {
alert(status + " - " + xhr.responseText);
}
});
To send the JSON data to my Web API method.
This is the JSON that is sent to the server:
{
"BlogTitle": "Sample Post",
"BlogHTML": "<p><strong>Sample JSON Blog Post</strong></p>\n\n<h1><strong>It never works :( </strong></h1>\n",
"BlogThumbnail": "http://mysystemURL/SamplePost/What.jpg",
"BlogSummary": "This is a sample post",
"BlogFQURL": "Sample_Post",
"BlogTags": [
"json",
"devlopment",
"newtag",
""
],
"BlogCategory": 1
}
My WEB API method received the JSON data correctly. The RAW string value looks like this:
"{\"BlogTitle\":\"Sample Post\",\"BlogHTML\":\"<p><strong>Sample JSON Blog Post</strong></p>\\n\\n<h1><strong>It never Works :(</strong></h1>\\n\",\"BlogThumbnail\":\"http://mysystemURL/SamplePost/What.jpg\",\"BlogSummary\":\"This is a sample post\",\"BlogFQURL\":\"Sample_Post\",\"BlogTags\":\"[\\\"json\\\",\\\"devlopment\\\",\\\"newtag\\\",\\\"\\\"]\",\"BlogCategory\":1}"
when I use the JSON visulizer on my data I get this:
I use this BlogPost vari = JsonConvert.DeserializeObject<BlogPost>(value); to deserialize my object but everything stays null
My BlogPost Object looks like this:
public class BlogPost
{
public int BlogPostID { get; set; }
public string BlogPostTitle { get; set; }
public string BlogPostHTML { get; set; }
public string BlogPostThumbnailURL { get; set; }
public string BlogPostSummary { get; set; }
public string BlogPostFQURL { get; set; }
public int BlogPostCategory { get; set; }
public List<TagDTO> BlogPostTags { get; set; }
}
I am really stumped.. Any help would be greatly appreciated!
Your property names don't match. The C# object's properties are BlogPost* and the JSON has Blog*, without the Post.
Correct the names either on the Javascript or on the C# side or use the JsonProperty attribute to specify the name of the serialized property.

Ajax data into MVC model

Our very simple models:
public class OrderSubmissionProductViewModel
{
public int Id { get; set; }
public decimal Price { get; set; }
public int Qty { get; set; }
}
public class OrderSubmissionViewModel
{
public int CustomerId { get; set; }
public int AccountId { get; set; }
public OrderSubmissionProductViewModel[] Products { get; set; }
}
The AJAX:
$.ajax({
url: self.urlSubmitOrder,
data: JSON.stringify({ submission: submission }),
type: 'POST',
success: function () { alert("Submitted"); },
fail: function () { alert("Failed"); }
});
The MVC controller has this method signature:
public ActionResult SubmitAdminOrder(OrderSubmissionViewModel submission)
{ ... }
This is what the POST looks like:
{"submission":{"CustomerId":43,"AccountId":"20000","Products":[{"Id":4,"Price":100,"Qty":1},{"Id":6,"Price":14,"Qty":1}]}}
I can hit a breakpoint in the controller method, and the model is not null, but all of its properties are default values. It's not getting bound correctly. What am I doing wrong?
We're using ASP.Net MVC 4.
Make sure the submission object isn't empty and can you try adding a contentType to the ajax options?
$.ajax({
url: self.urlSubmitOrder,
data: JSON.stringify({ submission: submission }),
type: 'POST',
contentType: "application/json; charset=utf-8",
success: function () { alert("Submitted"); },
fail: function () { alert("Failed"); }
});
Or take a look at this post Pass viewmodel with two objects to controller using Json

Categories

Resources