Convert JsonResult to ViewResult in Filter with ASP.NET Core

493 Views Asked by At

My task is to make sure that a controller can return a Json-like response or a View based on who calls the corresponding API. To do that, I changed the returns of each controller I made so that they give a JsonResult and I created a class that extends IResultFilter.

In the OnResultExecuting method extended by IResultFilter I inserted my implementation: I examine the Accept header of the call and if it contains text/html I have to convert the JsonResult into a ViewResult, using as a viewModel only the Json Value body (which also contains other information about the call that I don't need in the ViewModel). But not being in a controller, I can not create a ViewResult object.

How can I do that?

1

There are 1 best solutions below

1
J.Loscos On

In a IResultFilter the Result property is readonly. But it's not the case in IActionFilter. There you can override the Result :

public class TestFilter : Attribute, IActionFilter
{
    public void OnActionExecuted(ActionExecutedContext context)
    {
        var controller = context.Controller as Controller;
        controller.ViewData.Model = ((JsonResult)context.Result).Value;
        context.Result = new ViewResult()
        {
            ViewName = "Test",
            ViewData = controller.ViewData
        };
    }

    public void OnActionExecuting(ActionExecutingContext context)
    {  
    }
}