这个概念用于MVC Web 应用程序。
.NET Framework 4.x提供了几个触发动作的属性,例如:(ExceptionFilterAttribute
处理异常)、AuthorizeAttribute
(处理授权)。两者都定义在System.Web.Http.Filters
.
例如,您可以定义自己的授权属性,如下所示:
public class myAuthorizationAttribute : AuthorizeAttribute
{
protected override bool IsAuthorized(HttpActionContext actionContext)
{
// do any stuff here
// it will be invoked when the decorated method is called
if (CheckAuthorization(actionContext))
return true; // authorized
else
return false; // not authorized
}
}
然后,在您的控制器类中,您装饰应该使用您的授权的方法,如下所示:
[myAuthorization]
public HttpResponseMessage Post(string id)
{
// ... your code goes here
response = new HttpResponseMessage(HttpStatusCode.OK); // return OK status
return response;
}
每当Post
调用方法时,都会在IsAuthorized
方法内部的代码执行之前myAuthorization
调用Attribute内部的方法。Post
如果您false
在该IsAuthorized
方法中返回,则表示未授予授权并且该方法的执行Post
中止。
为了理解它是如何工作的,让我们看一个不同的例子: The ExceptionFilter
,它允许通过使用属性过滤异常,用法与上面所示的类似(您可以在此处AuthorizeAttribute
找到有关其用法的更详细说明)。
要使用它,请DivideByZeroExceptionFilter
从此处ExceptionFilterAttribute
所示的类派生类,并覆盖该方法:OnException
public class DivideByZeroExceptionFilter : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext actionExecutedContext)
{
if (actionExecutedContext.Exception is DivideByZeroException)
{
actionExecutedContext.Response = new HttpResponseMessage() {
Content = new StringContent("A DIV error occured within the application.",
System.Text.Encoding.UTF8, "text/plain"),
StatusCode = System.Net.HttpStatusCode.InternalServerError
};
}
}
}
然后使用下面的演示代码来触发它:
[DivideByZeroExceptionFilter]
public void Delete(int id)
{
// Just for demonstration purpose, it
// causes the DivideByZeroExceptionFilter attribute to be triggered:
throw new DivideByZeroException();
// (normally, you would have some code here that might throw
// this exception if something goes wrong, and you want to make
// sure it aborts properly in this case)
}
现在我们知道它是如何使用的,我们主要对实现感兴趣。以下代码来自 .NET Framework。它在内部使用接口IExceptionFilter
作为合约:
namespace System.Web.Http.Filters
{
public interface IExceptionFilter : IFilter
{
// Executes an asynchronous exception filter.
// Returns: An asynchronous exception filter.
Task ExecuteExceptionFilterAsync(
HttpActionExecutedContext actionExecutedContext,
CancellationToken cancellationToken);
}
}
ExceptionFilterAttribute
本身定义如下:
namespace System.Web.Http.Filters
{
// Represents the attributes for the exception filter.
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method,
Inherited = true, AllowMultiple = true)]
public abstract class ExceptionFilterAttribute : FilterAttribute,
IExceptionFilter, IFilter
{
// Raises the exception event.
// actionExecutedContext: The context for the action.
public virtual void OnException(
HttpActionExecutedContext actionExecutedContext)
{
}
// Asynchronously executes the exception filter.
// Returns: The result of the execution.
Task IExceptionFilter.ExecuteExceptionFilterAsync(
HttpActionExecutedContext actionExecutedContext,
CancellationToken cancellationToken)
{
if (actionExecutedContext == null)
{
throw Error.ArgumentNull("actionExecutedContext");
}
this.OnException(actionExecutedContext);
return TaskHelpers.Completed();
}
}
}
在内部ExecuteExceptionFilterAsync
,方法OnException
被调用。因为您已经如前所示覆盖了它,所以现在可以由您自己的代码处理该错误。
如 OwenP 的回答中提到的,还有一个商业产品PostSharp,它可以让您轻松地做到这一点。这是一个如何使用 PostSharp 执行此操作的示例。请注意,有一个 Express 版本可供您免费使用,甚至可以用于商业项目。
PostSharp 示例(有关完整说明,请参见上面的链接):
public class CustomerService
{
[RetryOnException(MaxRetries = 5)]
public void Save(Customer customer)
{
// Database or web-service call.
}
}
这里的属性指定Save
如果发生异常,该方法最多被调用 5 次。以下代码定义了此自定义属性:
[PSerializable]
public class RetryOnExceptionAttribute : MethodInterceptionAspect
{
public RetryOnExceptionAttribute()
{
this.MaxRetries = 3;
}
public int MaxRetries { get; set; }
public override void OnInvoke(MethodInterceptionArgs args)
{
int retriesCounter = 0;
while (true)
{
try
{
args.Proceed();
return;
}
catch (Exception e)
{
retriesCounter++;
if (retriesCounter > this.MaxRetries) throw;
Console.WriteLine(
"Exception during attempt {0} of calling method {1}.{2}: {3}",
retriesCounter, args.Method.DeclaringType, args.Method.Name, e.Message);
}
}
}
}