什么是Request.InputStream以及何时使用它?

Asd*_*dfg 12 asp.net-mvc jquery asp.net-mvc-3

问题很简单.什么是Request.InputStream何时使用它.是否总是用于读取在post请求中发送的整个html主体或仅发送一些参数?为什么我不能通过在Ajax请求中传递数据作为参数发送到我的服务器端代码?

在示例中,我可以传递参数,data:或者我可以读取参数Request.InputStream.我什么时候应该使用哪一个?

例:

在控制器中:

    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");
    }
Run Code Online (Sandbox Code Playgroud)

Ajax请求:

        $.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);
            }
        });
Run Code Online (Sandbox Code Playgroud)

Dar*_*rov 8

Request.InputStream允许您访问原始请求数据.如果使用某些标准格式(例如,application/x-www-form-urlencodedmultipart/form-data某些其他格式,默认模型绑定器可以理解您不需要使用的格式)格式化此数据Request.InputStream.ASP.NET将解析请求值,您将能够直接使用它们访问它们Request[...].当然,在ASP.NET MVC,你甚至都不需要用Request[...],因为你可以定义你的控制器动作将作为参数,并留下模型绑定从请求转让其性能视图模型.

有时您可能想要访问原始请求流.例如,您发明了一些自定义协议,客户端在请求流中发送一些自定义格式的数据.这些情况非常罕见,因为发明自定义协议并不常见.

现在回到你的问题.在您的情况下,您可以定义视图模型:

public class MyViewModel
{
    public string SomeData { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

您的控制器操作将作为参数:

public ActionResult GetSomeData(MyViewModel model)
{
    // model.SomeData will contain the Hello string that the client sent
    return Json("something");
}
Run Code Online (Sandbox Code Playgroud)

在客户端上,我建议你使用原生JSON.stringify内置于现代浏览器中的方法,将请求javascript文字序列化为JSON字符串,而不是像你一样手动编写JSON:

$.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);
    }
});
Run Code Online (Sandbox Code Playgroud)