有什么方法可以在ASP.NET MVC 3 RC2中禁用JSON ModelBinder? [英] Is there any way to disable the JSON ModelBinder in ASP.NET MVC 3 RC2?

查看:66
本文介绍了有什么方法可以在ASP.NET MVC 3 RC2中禁用JSON ModelBinder?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在ASP.NET MVC 3 RC2中,如果Content-Type设置为application/json,则默认的ModelBinder将自动解析请求正文.问题是,这将Request.InputStream留在了流的末尾.这意味着,如果您尝试使用自己的代码读取输入流,请先将其重新设置为开头:

In ASP.NET MVC 3 RC2, the default ModelBinder will automatically parse the request body if the Content-Type is set to application/json. Problem is, this leaves the Request.InputStream at the end of the stream. This means that if you try to read the input stream using your own code, you first have reset it back to the beginning:

// 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进行额外的解析.有什么办法吗?

Since I'm using Json.NET to do my serialization/deserialization, I'd like to disable the default ModelBinder from doing this extra parsing. Is there any way to do that?

推荐答案

您可以在Global.asax的Application_Start中添加以下内容:

You can put the following in Application_Start in your Global.asax:

ValueProviderFactories.Factories.Remove(
            ValueProviderFactories.Factories.OfType<JsonValueProviderFactory>().First());

这假定只有一种类型(默认情况下为该类型),但是如果存在多个类型,则可以很容易地将其更改为可工作.我不认为如果您正在寻找更干净的方式.

This assumes there is only one of that type (which by default there is), but it can easily be changed to work if there is more than one. I don't believe there is a cleaner way if that is what you are looking for.

这篇关于有什么方法可以在ASP.NET MVC 3 RC2中禁用JSON ModelBinder?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆