Return JsonResult using an ActionFilter on an ActionResult in a controller

前端 未结 3 988
谎友^
谎友^ 2021-01-18 00:39

I want to return the Model (data) of a controller in different formats (JavaScript/XML/JSON/HTML) using ActionFilter\'s. Here\'s where I\'m at so far:

The ActionFilt

相关标签:
3条回答
  • 2021-01-18 01:17

    Have you tried implementing your filter code in the OnActionExecuted method, instead of OnResultExecuting? It's possible that by the time the latter is fired, it's too late to change the result (the semantics being, "OK, we have the result in hand, and this hook is fire right before this result right here is executed"), but I don't have the time right now to go check the MVC source to be sure.

    0 讨论(0)
  • 2021-01-18 01:25

    This was what I was looking for:

    public class ResultFormatAttribute : ActionFilterAttribute, IActionFilter
    {
        void IActionFilter.OnActionExecuted(ActionExecutedContext context)
        {
            context.Result = new JsonResult
            {
                Data = ((ViewResult)context.Result).ViewData.Model
            };
        }
    }
    
    0 讨论(0)
  • 2021-01-18 01:38

    Have you tried:

    return Json(entries);
    

    with a return type of JsonResult on the controller action?

    0 讨论(0)
提交回复
热议问题