ASP.Net MVC编写自定义Attribute

【字号: 日期:2023-07-21浏览:28作者:雯心

问题描述

我在将近一半的方法中,需要执行一段特定代码。这段代码负责将HTTP返回头中增加一个Header。如果复制粘贴这些代码实在太低效率了。请问如何写一个自定义Attribute来实现加了这个Attribute的方法就具有这些特性呢?

同时,我也在近一半的方法中(另一半只需要留给ASP.Net自己处理),需要对这个方法Try Catch住,使得发生异常时能够被我自己捕获,异常的处理代码都是相同的。如果复制粘贴这些代码,实在太低效率了。如何写一个自定义Attribute来实现加了这个Attribute的方法就具有这些特性呢?

问题解答

回答1:

比如在header加入允许跨域请求

public class AllowOriginAttribute : ActionFilterAttribute{ public override void OnActionExecuting(ActionExecutingContext filterContext) { filterContext.RequestContext.HttpContext.Response.AddHeader('Access-Control-Allow-Origin', '*'); base.OnActionExecuting(filterContext); }}

将异常抛给最上层进行统一处理。写一个父级Controller,其他Controller集成它,然后重写这个可统一处理异常

protected override void OnException(ExceptionContext context){ base.OnException(context); //处理异常 context.ExceptionHandled = true; context.HttpContext.Response.Clear(); context.HttpContext.Response.StatusCode = GetStatusCodeForException(context); context.Result = ...//判断是否是json,返回不同的结果 context.HttpContext.Response.TrySkipIisCustomErrors = true;}

回答2:

自定义特性继承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); }}

相关文章: