[英]Convert JsonResult to ViewResult in Filter with ASP.NET Core
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. 我的任务是确保控制器可以根据调用相应API的人返回类似Json的响应或View。 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 .
为此,我更改了每个控制器的返回值,以便它们提供JsonResult,并创建了一个扩展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). 在IResultFilter扩展的OnResultExecuting方法中,我插入了我的实现:我检查了调用的Accept标头,并且如果其中包含text / html,我必须将JsonResult转换为ViewResult ,仅将Json Value主体(还包含Json Value主体)用作viewModel有关ViewModel中不需要的呼叫的其他信息)。 But not being in a controller, I can not create a ViewResult object.
但是由于不在控制器中,所以无法创建ViewResult对象。
How can I do that? 我怎样才能做到这一点?
In a IResultFilter the Result property is readonly. 在IResultFilter中,Result属性为只读。 But it's not the case in IActionFilter.
但是在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)
{
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.