質問は本当に簡単です。 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");
}
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);
}
});
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.
しかし、生の要求ストリームにアクセスしたい場合があります。たとえば、カスタムプロトコルをいくつか作成し、クライアントが要求ストリームにカスタムフォーマットのデータを送信するとします。カスタムプロトコルの発明はあまり一般的ではないので、これらのケースは非常にまれです。
今あなたの質問に戻る。あなたの場合、ビューモデルを定義することができます:
public class MyViewModel
{
public string SomeData { get; set; }
}
あなたのコントローラーアクションは引数として取るでしょう:
public ActionResult GetSomeData(MyViewModel model)
{
//model.SomeData will contain the Hello string that the client sent
return Json("something");
}
クライアントでは、現代のブラウザにJSONを組み込んだ JSON.stringify
メソッドを使用することをお勧めします.JSONを手動で記述するのではなく、JSON文字列にリクエストJavaScriptのリテラルを直列化します。
$.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);
}
});