此概念用于 MVC 网络应用程序。
.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
}
}
然后,在您的 controller 类中,您装饰应该使用您的授权的方法,如下所示:
[myAuthorization]
public HttpResponseMessage Post(string id)
{
// ... your code goes here
response = new HttpResponseMessage(HttpStatusCode.OK); // return OK status
return response;
}
每当Post方法被调用时,它都会在myAuthorization属性内调用IsAuthorized方法在Post方法内的代码被执行之前。
如果您在IsAuthorized 方法中返回false,则表示未授予授权并且方法Post 的执行将中止。
要了解它是如何工作的,让我们看一个不同的例子:ExceptionFilter,它允许使用属性过滤异常,用法与上面显示的AuthorizeAttribute 类似(您可以找到更详细的用法说明here)。
要使用它,从ExceptionFilterAttribute 派生DivideByZeroExceptionFilter 类,如here 所示,并覆盖方法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,它可以让您轻松地做到这一点。 Here 是一个如何使用 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);
}
}
}
}