gpt4 book ai didi

asp.net-mvc - 如何全局覆盖影响 MVC 中所有 Controller 的方法?

转载 作者:行者123 更新时间:2023-12-03 07:21:52 25 4
gpt4 key购买 nike

我在 MVC 中遇到了有关 MaxJsonLength 的问题。当我返回 json() 时出现问题。然后我找到了解决方案here (请阅读本文)由 fanisch 回答。现在我有很多 Controller ,其中存在 MaxJsonLength 问题。我想全局重写这个方法。

protected override JsonResult Json(object data, string contentType, System.Text.Encoding contentEncoding, JsonRequestBehavior behavior)
{
return new JsonResult()
{
Data = data,
ContentType = contentType,
ContentEncoding = contentEncoding,
JsonRequestBehavior = behavior,
MaxJsonLength = Int32.MaxValue
};
}

我该怎么做?有没有办法在全局范围内实现此方法,或者我应该使用操作过滤器?

最佳答案

创建扩展方法的最简单方法(完全同意OP上的其他评论)。这是您的方法在 OP 中作为扩展方法的实现。您可以根据需要重命名它。我还为参数添加了一些默认值,这些默认值与 Controller 的方法重载中使用的参数相同。

public static class ControllerExtensions {
public static JsonResult AsJson(this Controller controller, object data, JsonRequestBehavior behavior = JsonRequestBehavior.AllowGet, string contentType = null, System.Text.Encoding contentEncoding = null)
{
return new JsonResult()
{
Data = data,
ContentType = contentType,
ContentEncoding = contentEncoding,
JsonRequestBehavior = behavior,
MaxJsonLength = Int32.MaxValue
};
}
}

// how to call from inside an action (method) on a controller
public class SomeController : Controller {
public JsonResult GetSomething(){
return this.AsJson(new {prop1 = "testing"});
}
}

有关扩展方法的更多信息,请参阅 Extension Methods

关于asp.net-mvc - 如何全局覆盖影响 MVC 中所有 Controller 的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39594188/

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