ASP.NET MVC: How to create an action filter to output JSON?

后端 未结 3 1810
抹茶落季
抹茶落季 2021-01-03 08:03

My second day with ASP.NET MVC and my first request for code on SO (yep, taking a short cut).

I am looking for a way to create a filter that intercepts the current o

相关标签:
3条回答
  • 2021-01-03 08:22

    You haven't mentioned only returning the JSON conditionally, so if you want the action to return JSON every time, why not use:

    public JsonResult Index()
    {
        var model = new{ foo = "bar" };
        return Json(model);
    }
    
    0 讨论(0)
  • 2021-01-03 08:24

    maybe this post could help you the right way. The above post is also a method

    0 讨论(0)
  • 2021-01-03 08:26

    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.

    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();
    }
    
    0 讨论(0)
提交回复
热议问题