gpt4 book ai didi

c# - 有没有办法在 ASP.NET MVC 3 RC2 中禁用 JSON ModelBinder?

转载 作者:可可西里 更新时间:2023-11-01 08:41:41 25 4
gpt4 key购买 nike

在 ASP.NET MVC 3 RC2 中,如果 Content-Type 设置为 application/json,则默认的 ModelBinder 将自动解析请求主体。问题是,这会在流的末尾留下 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());

这假设只有一种类型(默认情况下有),但如果有多种类型,它可以很容易地更改为有效。如果您正在寻找这种方法,我认为没有更简洁的方法。

关于c# - 有没有办法在 ASP.NET MVC 3 RC2 中禁用 JSON ModelBinder?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4496237/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com