在 ASP.NET MVC 3 RC2 中,默认的 ModelBinder 将自动解析请求体,如果Content-Type
被设定为application/json
。问题是,这留下了Request.InputStream
在流的末尾。这意味着,如果您尝试使用自己的代码读取输入流,则首先将其重置回开头:
// client sends HTTP request with Content-Type: application/json and a JSON
// string in the body
// requestBody is null because the stream is already at the end
var requestBody = new StreamReader(Request.InputStream).ReadToEnd();
// resets the position back to the beginning of the input stream
var reader = new StreamReader(Request.InputStream);
reader.BaseStream.Position = 0;
var requestBody = reader.ReadToEnd();
由于我正在使用Json.NET
为了进行序列化/反序列化,我想禁用默认的 ModelBinder 进行额外的解析。有什么办法可以做到这一点吗?
您可以将以下内容放入 Global.asax 的 Application_Start 中:
ValueProviderFactories.Factories.Remove(
ValueProviderFactories.Factories.OfType<JsonValueProviderFactory>().First());
这假设只有一种该类型(默认情况下有),但如果有多个类型,则可以轻松更改为工作。如果您正在寻找的话,我不相信有更干净的方法。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)