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);
}
}
精彩评论