C# ASP.NET MVC:如何创建一个动作过滤器来输出 JSON?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/686753/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ASP.NET MVC: How to create an action filter to output JSON?
提问by aleemb
My second day with ASP.NET MVC and my first request for code on SO (yep, taking a short cut).
我在 ASP.NET MVC 的第二天和我对 SO 代码的第一个请求(是的,走捷径)。
I am looking for a way to create a filter that intercepts the current output from an Action and instead outputs JSON (I know of alternate approachesbut this is to help me understand filters). I want to ignore any views associated with the action and just grab the ViewData["Output"], convert it to JSON and send it out the client. Blanks to fill:
我正在寻找一种方法来创建一个过滤器,该过滤器拦截来自 Action 的当前输出并输出 JSON(我知道其他方法,但这是为了帮助我理解过滤器)。我想忽略与操作相关的任何视图,只需获取 ViewData["Output"],将其转换为 JSON 并将其发送给客户端。填空:
TestController.cs:
TestController.cs:
[JSON]
public ActionResult Index()
{
ViewData["Output"] = "This is my output";
return View();
}
JSONFilter.cs:
JSONFilter.cs:
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
/*
* 1. How to override the View template and set it to null?
* ViewResult { ViewName = "" } does not skip the view (/Test/Index)
*
* 2. Get existing ViewData, convert to JSON and return with appropriate
* custom headers
*/
}
Update: Community answers led to a fuller implementation for a filter for JSON/POX.
更新:社区答案导致了 JSON/POX 过滤器的更完整实现。
采纳答案by tvanfosson
I would suggest that what you really want to do is use the Model rather than arbitrary ViewData
elements and override OnActionExecuted
rather than OnActionExecuting
. That way you simply replace the result with your JsonResult
before it gets executed and thus rendered to the browser.
我建议您真正想做的是使用 Model 而不是任意ViewData
元素并覆盖OnActionExecuted
而不是OnActionExecuting
. 这样,您只需在结果JsonResult
被执行并呈现给浏览器之前将其替换为您的结果。
public class JSONAttribute : ActionFilterAttribute
{
...
public override void OnActionExecuted( ActionExecutedContext filterContext)
{
var result = new JsonResult();
result.Data = ((ViewResult)filterContext.Result).Model;
filterContext.Result = result;
}
...
}
[JSON]public ActionResult Index()
{
ViewData.Model = "This is my output";
return View();
}
回答by JSC
回答by Troy
You haven't mentioned only returning the JSON conditionally, so if you want the action to return JSON every time, why not use:
您没有提到仅有条件地返回 JSON,因此如果您希望操作每次都返回 JSON,为什么不使用:
public JsonResult Index()
{
var model = new{ foo = "bar" };
return Json(model);
}