Asp.Net Mvc - 在OnResultExecut* 拦截Action返回的HTML

时间:2023-12-25 18:50:19

在Asp.Net MVC项目中通过重写ActionFilterAttribute中的方法,我们就可以在轻松的在Action方法执行前后做一些特殊的操作如:[身份认证、日志记录、内容截取等]。

但是我们要想在OnResultExecuting\OnResultExecuted中获取Actioin返回的HTML该怎么做呢?

废话不多说先看代码如下:

Asp.Net Mvc - 在OnResultExecut* 拦截Action返回的HTML

运行结果如下:

Asp.Net Mvc - 在OnResultExecut* 拦截Action返回的HTML

微软官方的ActionFilterAttribute定义如下:

   using System;
namespace System.Web.Mvc
{
/// <summary>Represents the base class for filter attributes.</summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public abstract class ActionFilterAttribute : FilterAttribute, IActionFilter, IResultFilter
{
/// <summary>Called by the ASP.NET MVC framework before the action method executes.</summary>
/// <param name="filterContext">The filter context.</param>
public virtual void OnActionExecuting(ActionExecutingContext filterContext)
{
}
/// <summary>Called by the ASP.NET MVC framework after the action method executes.</summary>
/// <param name="filterContext">The filter context.</param>
public virtual void OnActionExecuted(ActionExecutedContext filterContext)
{
}
/// <summary>Called by the ASP.NET MVC framework before the action result executes.</summary>
/// <param name="filterContext">The filter context.</param>
public virtual void OnResultExecuting(ResultExecutingContext filterContext)
{
}
/// <summary>Called by the ASP.NET MVC framework after the action result executes.</summary>
/// <param name="filterContext">The filter context.</param>
public virtual void OnResultExecuted(ResultExecutedContext filterContext)
{
}
}
}