首页 > 代码库 > 使用无注解属性的过滤

使用无注解属性的过滤

mvc中使用过滤器常规的办法是使用注解属性。然而还有另外一种办法,Controller类也实现了IAuthorizationFilter、IActionFilter、IResultFilter和IExceptionFilter接口。所以可以在

Controller类中直接重写相应的方法就可以使该Controller下的所有Action就被应用于所重写的过滤。

public class HomeController : Controller
{
private Stopwatch timer;
[Authorize(Users = "admin")]
public string Index()
{
return "This is the Index action on the home controller";
}
[GoogleAuth]
[Authorize(Users ="lq@google.com")]
public string List() {
return "this is the List action on the Home controller";
}
//[RangeException]
[HandleError(ExceptionType =typeof(ArgumentOutOfRangeException),View ="RangeError")]
public string RangeTest(int id) {
if (id > 100)
{
return String.Format("The id value is:{0}", id);
}
else {
throw new ArgumentOutOfRangeException("id",id,"");
}
}

public string FilterTest() {
return "this is the filterTest action";
}
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
timer = Stopwatch.StartNew();
}

protected override void OnResultExecuted(ResultExecutedContext filterContext)
{
timer.Stop();
filterContext.HttpContext.Response.Write(string.Format("<div> Total elapsed time:{0}</div>",timer.Elapsed.TotalSeconds));
}
}

 

使用无注解属性的过滤