what is Request.InputStream and when to use it?

后端 未结 1 1130
隐瞒了意图╮
隐瞒了意图╮ 2021-01-11 10:23

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 para

相关标签:
1条回答
  • 2021-01-11 11:28

    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);
        }
    });
    
    0 讨论(0)
提交回复
热议问题