如何检查操作结果是部分视图还是视图?
How to check if action result is partial view or view?
有什么方法可以在客户端找出执行了什么样的操作?我只想知道视图是由 PartialView
方法还是 View
方法生成的。
我查看了 headers,但没有找到有用的信息。
为了实现这一点,我可以通过覆盖 PartialView
方法将一些 headers 添加到 http 响应中。
protected override PartialViewResult PartialView(string viewName, object model)
{
Response.AddHeader("is-partial", "of_course_this_is_partial");
return base.PartialView(viewName, model);
}
但我想知道 MVC 5 中是否有任何内置解决方案?所以我不必使用自定义派生控制器 class 并在任何地方使用它。
您可以使用动作过滤器:
public class ResponseHeaderActionFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
}
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
}
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
// use filterContext.Result to see whether it's a partial or not
// filterContext.HttpContext.Response.AddHeader()..
}
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
}
}
如果您将其设为全局操作过滤器,它会自动执行,您不必从基本控制器继承或将其作为控制器的属性:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
// Register global filter
GlobalFilters.Filters.Add(new ResponseHeaderActionFilter());
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
这样,header 会自动添加到每个结果中。
有什么方法可以在客户端找出执行了什么样的操作?我只想知道视图是由 PartialView
方法还是 View
方法生成的。
我查看了 headers,但没有找到有用的信息。
为了实现这一点,我可以通过覆盖 PartialView
方法将一些 headers 添加到 http 响应中。
protected override PartialViewResult PartialView(string viewName, object model)
{
Response.AddHeader("is-partial", "of_course_this_is_partial");
return base.PartialView(viewName, model);
}
但我想知道 MVC 5 中是否有任何内置解决方案?所以我不必使用自定义派生控制器 class 并在任何地方使用它。
您可以使用动作过滤器:
public class ResponseHeaderActionFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
}
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
}
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
// use filterContext.Result to see whether it's a partial or not
// filterContext.HttpContext.Response.AddHeader()..
}
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
}
}
如果您将其设为全局操作过滤器,它会自动执行,您不必从基本控制器继承或将其作为控制器的属性:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
// Register global filter
GlobalFilters.Filters.Add(new ResponseHeaderActionFilter());
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
这样,header 会自动添加到每个结果中。