Reputation: 6609
I am trying to POST
Json
data to API
and read the value from the key using the HttpContext.Current.Request
object.
Client Side:
var data = { Name: "Tom" };
$.ajax({
type: "POST",
url: url,
data: JSON.stringify(data),
dataType: "json",
contentType: "application/json",
success: function (response) {
}
});
In API:
[HttpPost]
[Route("UploadProduct")]
public HttpResponseMessage Upload()
{
if (string.IsNullOrEmpty(HttpContext.Current.Request["Name"]))
return "Name is missing";
//... removed for brevity
}
Why key Name is always empty ?
I know Json
data will bind to model object only. But like to know if it's possible to get data from HttpContext.Current.Request
object by making some changes in client side ?
Upvotes: 0
Views: 1419
Reputation: 9190
OK, try this:
Change contentType
to application/x-www-form-urlencoded
, remove the JSON.stringify()
and just pass the JSON data as is. With this you should be able to get the form values with this.Request.Form["Name"]
or simply this.Request["Name"]
or even HttpContext.Current.Request["Name"]
.
When you POST
data to server (particularly with content types other than application/x-www-form-urlencoded
), the content is being placed in the Request
body, and so it's not going to be available for reading in the Request.Form
name-value collection object.
For nested data, you can query the values just like you would with Javascript object literal, something like:
var data = {
Name: "Tom",
Address: {
Street: "ABC"
}
}
this.Request.Form["Address[Street]"] // ABC
Although it's always better to use model binding whenever possible.
Upvotes: 2