学习之-ASP.NET MVC Filter

时间:2021-01-01 15:26:51

MVC Filter 是典型的AOP应用,对MVC框架处理客户端请求注入额外的一些逻辑,如日志记录、缓存处理、异常处理和权限验证,性能检测(横切关注点),而这些逻辑通常与主要业务无关,被独立分开作为公用的部分,降低模块之间的耦合度 。

ASP.NET MVC 有四种基本过滤器

过滤器类型

接口

默认实现

描述

Authorization

IAuthorizationFilter

AuthorizationAttribute

最先运行,在任何其他过滤器或动作方法之前

Action

IActionFilter

ActionFilterAttribute

在动作方法前后运行

Result

IResultFilter

ActionResultAttribute

在动作结果被执行前后

Exception

IExceptionFilter

HandlerErrorAttribute

仅在过滤器、动作发生异常时

示例代码

Authorization:输入的名称为空则直接跳转页面

public class MyAuthorizeFliter:AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
var Name = System.Web.HttpContext.Current.Request.QueryString["name"];
var IP = System.Web.HttpContext.Current.Request.UserHostAddress; if (string.IsNullOrEmpty(Name))
{
filterContext.Result = new RedirectResult("/Index/Msg");
//filterContext.Result = new RedirectToRouteResult("Default", new RouteValueDictionary(new { controller = "Index", action = "Msg" }));
//filterContext.HttpContext.Response.Redirect("/Index/Msg", true);
//filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Index", action = "Msg" }));
}
//base.OnAuthorization(filterContext);
}
}

Action和Result

控制器代码

        [MyActionFilter]
[Route("Index/PostMethod")]
public ActionResult PostMethod()
{
var aa = Request.QueryString["name"];
Logs.WriteLine("正常执行。。。");
return View("Success");
}

过滤器

 public override void OnActionExecuting(ActionExecutingContext filterContext)
{
Logs.WriteLine("执行前。。。" + DateTime.Now.ToString());
base.OnActionExecuting(filterContext);
}
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
Logs.WriteLine("执行后。。。");
base.OnActionExecuted(filterContext);
}
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
Logs.WriteLine("结果前。。。");
base.OnResultExecuting(filterContext);
}
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
Logs.WriteLine("结果后。。。");
base.OnResultExecuted(filterContext);
}

运行结果:

学习之-ASP.NET MVC Filter


Exception

 public class MyExceptionFilter:HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
Exception ex = filterContext.Exception;
Logs.WriteLine("出错了"+ex.Message);
base.OnException(filterContext);
}
}

加入自定义过滤器

可以加在三个地方

1.一个是控制器的上方,(控制器下所有的action将注入过滤器)如下代码:

 [MyExceptionFilter]
public class IndexController : Controller
{
// GET: Index
[HttpGet]
public ActionResult Home()
{
return View("Home");
}
}

2.指定action方法

[MyAuthorizeFliter]
public ActionResult PostMethod()
{
return View("Success");
}

3.全局,在App_Start下的FilterConfing添加代码,如果是WebApi则是要添加到WebApiConfig.cs

 public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
}