我在将近一半的方法中,需要执行一段特定代码。这段代码负责将HTTP返回头中增加一个Header。如果复制粘贴这些代码实在太低效率了。请问如何写一个自定义Attribute来实现加了这个Attribute的方法就具有这些特性呢?
同时,我也在近一半的方法中(另一半只需要留给ASP.Net自己处理),需要对这个方法Try Catch住,使得发生异常时能够被我自己捕获,异常的处理代码都是相同的。如果复制粘贴这些代码,实在太低效率了。如何写一个自定义Attribute来实现加了这个Attribute的方法就具有这些特性呢?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
自定义特性继承ActionFilterAttribute,重写下OnActionExecuting方法
namespace System.Web.Mvc { // // 摘要: // 表示筛选器特性的基类。 [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)] public abstract class ActionFilterAttribute : FilterAttribute, IActionFilter, IResultFilter { // // 摘要: // 初始化 System.Web.Mvc.ActionFilterAttribute 类的新实例。 protected ActionFilterAttribute(); // // 摘要: // 在执行操作方法后由 ASP.NET MVC 框架调用。 // // 参数: // filterContext: // 筛选器上下文。 public virtual void OnActionExecuted(ActionExecutedContext filterContext); // // 摘要: // 在执行操作方法之前由 ASP.NET MVC 框架调用。 // // 参数: // filterContext: // 筛选器上下文。 public virtual void OnActionExecuting(ActionExecutingContext filterContext); // // 摘要: // 在执行操作结果后由 ASP.NET MVC 框架调用。 // // 参数: // filterContext: // 筛选器上下文。 public virtual void OnResultExecuted(ResultExecutedContext filterContext); // // 摘要: // 在执行操作结果之前由 ASP.NET MVC 框架调用。 // // 参数: // filterContext: // 筛选器上下文。 public virtual void OnResultExecuting(ResultExecutingContext filterContext); } }