如何从Action Attribute返回Json对象?

时间:2010-04-20 20:20:40

标签: asp.net-mvc

当重写OnActionExecuting时,如何在不传递操作的情况下返回Json结果?

2 个答案:

答案 0 :(得分:12)

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
   if (/* whatever */)
   {
      var result = new JsonResult();
      result.Data = /* json data */;
      filterContext.Result = result;
      return;
   }

   base.OnActionExecuting(filterContext);
   return;
}

答案 1 :(得分:0)

我发现使用Json.NET生成json输出很有用。这具有许多优点,例如,在某些条件下可以隐藏JSON属性。

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
    if (/* whatever */)
    {
        var result = new ResultModel(); // your json model
        ContentResult content = new ContentResult();
        content.ContentType = "application/json";
        content.Content = JsonConvert.SerializeObject(result);
        filterContext.Result = content;
        base.OnActionExecuting(filterContext);
    }
}