Question is really simple. What is Request.InputStream
and when to use it. Is it always used to read entire html body sent in the post request or only some parameters sent in it? Why should i not send data as a parameter to my server side code by passing it in the Ajax request?
In the example i can either pass the parameter in the data:
or i can read the parameter in the Request.InputStream
. When should i use which one?
Example:
In controller:
public ActionResult GetSomeData(string someData)
{
Request.InputStream.Position = 0;
System.IO.StreamReader str = new System.IO.StreamReader(Request.InputStream);
string sBuf = str.ReadToEnd();
return Json("something");
}
Ajax Request:
$.ajax({
type: "POST",
url: "Home/GetSomeData",
data: "{someData:'Hello'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg);
// Insert the returned HTML into the <div>.
$('#dvResult').html(msg);
}
});
Request.InputStream
allows you to access the raw request data. If this data is formatted using some standard format such as application/x-www-form-urlencoded
or multipart/form-data
or some other format that the default model binder understands you do not need to use Request.InputStream
. ASP.NET will parse the request values and you will be able to access them directly using Request[...]
. Of course in ASP.NET MVC you don't even need to use Request[...]
because you can define a view model which your controller action will take as parameter and leave the model binder assign its properties from the request.
There are cases though when you might want to access the raw request stream. For example you have invented some custom protocol and the client sends some custom formatted data in the request stream. Those cases are very rare since inventing custom protocols is not very common.
Now back to your question. In your case you could define a view model:
public class MyViewModel
{
public string SomeData { get; set; }
}
which your controller action will take as argument:
public ActionResult GetSomeData(MyViewModel model)
{
// model.SomeData will contain the Hello string that the client sent
return Json("something");
}
and on the client I would recommend you using the JSON.stringify
method which is natively built into modern browsers to JSON serialize the request javascript literal into a JSON string instead of manually writing the JSON as you did:
$.ajax({
type: 'POST',
url: 'Home/GetSomeData',
data: JSON.stringify({ someData: 'Hello' }),
contentType: 'application/json; charset=utf-8',
success: function (msg) {
alert(msg);
// Insert the returned HTML into the <div>.
$('#dvResult').html(msg);
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With