开发者

How do I return a Json object from Action Attribute?

when overrid开发者_如何学JAVAing OnActionExecuting, how do I return a Json result without passing to action?


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

   base.OnActionExecuting(filterContext);
   return;
}


I find it useful to use Json.NET to generate the json output. This has many advantages, for example JSON properties can be hidden under certain conditions.

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);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜