Use of filters in ASP. NET mvc4

  • 2021-09-16 06:41:41
  • OfStack

Filters in mvc4

The filter (Filter) injects additional logic into the request processing of the MVC framework. Cross-attention is realized.

Cross-focus: Functions that are used for the whole application and are not suitable for a local location.

The filters are the annotation attributes (Attribute) of. NET, which add additional steps to the request processing pipeline.

The annotation attribute is a special. NET class derived from System. Attribute.

Can be attached to code elements such as classes, methods, properties, fields, etc. The purpose is to embed additional information into the compiled code so that it can be read back at run time.

Basic types of filters:

过滤器类型

接口

默认实现

描述

Authorization

IAuthorizationFilter

AuthorizationAttribute

最先运行

Action

IActionFilter

ActionFilterAttribute

在动作方法前后运行

Result

IResultFilter

ActionResultAttribute

在动作结果被执行前后

Exception

IExceptionFilter

HandlerErrorAttribute

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

Authorization Filter: IAuthorizationFilter


namespace System.Web.Mvc{

  //  Summary : Define the methods required for authorization filters. 

  public interface IAuthorizationFilter{

    //  Summary : Called when authorization is required. 

    //  Parameter :filterContext: Filter context. 

    void OnAuthorization(AuthorizationContext filterContext);

  }

}

Note:

Implementing the interface directly is actually a very dangerous thing; Therefore, it is easier to create a custom AuthorizeAttribute subclass and then implement authorization code.


public class CustomAuthAttribute:AuthorizeAttribute{

    /// <summary>

    ///  How to grant access to the request 

    /// </summary>

    /// <param name="httpContext"> Method of accessing requested information </param>

    protected override bool AuthorizeCore(HttpContextBase httpContext){

      return base.AuthorizeCore(httpContext);

    }

}

The primary reason for implementing the IAuthorizationFilter interface directly is to gain access to the AuthorizationContext passed to OnAuthorization (), through which a wider range of information (routing details, current controller, and action method information) can be obtained. Using interfaces not only has security risks, but also makes the logic established in authorization annotation attributes closely coupled with the controller, which destroys the separation of concerns and is inconvenient for maintenance.

Built-in authorization filter:

Although the AuthorizeAttribute class is used as the basis for custom filters, its AuthorizeCore () has its own implementation

When using AuthorizeAttribute directly, you can use its public attribute to specify authorization policies

AuthorizeAttribute Properties

名称

类型

描述

Users

String

1个逗号分隔的用户名列表,指定这些用户可以访问动作方法

Roles

String

1个逗号分隔的角色列表,用户必须至少有1个角色


public class HomeController : Controller{

    [Authorize(Users ="admin,steve,jacqui",Roles ="admin")]

    public ActionResult Index(){

      return View();

    }

}

Exception filter:


namespace System.Web.Mvc{

  //  Summary : Define the methods required for exception filters. 

  public interface IExceptionFilter{

    //  Summary : Called when an exception occurs. 

    //  Parameter :filterContext:

    //    Filter context. 

    void OnException(ExceptionContext filterContext);

  }

}

OnException () is called when an unhandled exception occurs. The argument to this method is an ExceptionContext object, which is derived from ControllerContext and provides many useful properties.

名称

类型

描述

Controller

ControllerBase

返回请求的控制器对象

HttpContext

HttpContextBase

提供对请求细节的访问及对响应的访问

IsChildAction

Bool

若是自动做则返回true

RequestContext

RequestContext

提供对HttpContext和路由数据的访问

RouteData

RouteData

返回请求的路由数据

Attributes inherited from ControllerContext

名称

类型

描述

ActionDescripter

ActionDescripter

提供动作方法的细节

Result

ActionResult

用于动作方法的结果,通过非空值可取消请求

Exception

Exception

未处理的异常

ExceptionHandled

Bool

如果另1个过滤器已经把这个异常标记为已处理则返回true

Implement custom exception filters


public class RangeExceptionAttribute : FilterAttribute, IExceptionFilter{

    public void OnException(ExceptionContext filterContext){

}

}

Use the built-in exception filter:

HandleErrorAttribute Properties

名称

类型

描述

ExceptionType

Type

由过滤器处理的异常类型

View

String

该过滤器渲染的视图模板名

Master

String

在渲染这个过滤器的视图时使用的布局名称

Preparations:

The HandleErrorAttribute filter takes effect when custom errors are enabled in the web. config file < system.web > Add 1 customErrors attribute to the node;


<system.web>

 <!-- Customize error page aa.html-->

  <customErrors mode="On" defaultRedirect="/Content/aa.html" />

 </system.web>

The default value of the Mode property is RemoteOnly During development, HandleErrorAttribute will not intercept exceptions, but HandleErrorAttribute becomes effective when the application is deployed to the production server and a request is made from another computer


 [HandleError(ExceptionType =typeof(ArgumentNullException),View ="Null")]

    public ActionResult Index(){

      return View();

  }

When rendering the view, the HandleErrorAttribute filter passes an HandleErrorInfo view model object, which is a wrapper that encapsulates the details of the exception

名称

类型

描述

ActionName

String

返回生成异常的Action名称

ControllerName

String

返回生成异常的Controller名称

Exception

Exception

返回此异常


@model HandleErrorInfo

@{ 

  ViewBag.Title = "Sorry";

}

<!DOCTYPE html>

<html>

<head>

  <meta name="viewport" content="width=device-width" />

</head>

<body>

@Model.Exception.StackTrace

</body>

</html>

Note: When using the HandleError filter, 1 must include Model. Exception. StackTrace otherwise the view will not be displayed to the user, the reference does not need to show the stack information to the user, so you can put the value into div and hide it

Motion filter

Multi-purpose filter for any purpose


namespace System.Web.Mvc{

  //  Summary : Defines the methods used in action filters. 

  public interface IActionFilter{

    //  Summary : Called after the operation method is executed. 

    //  Parameter :filterContext:

    //    Filter context. 

    void OnActionExecuted(ActionExecutedContext filterContext);

    //  Summary : Called before executing the action method. 

    //  Parameter :filterContext:

    //    Filter context. 

    void OnActionExecuting(ActionExecutingContext filterContext);

  }

}

ActionExecutingContext Properties

名称

类型

描述

ActionDescriptor

ActionDescriptor

动作方法的描述

Result

ActionResult

动作方法的结果,设置属性非空值,过滤器可以取消请求

ActionExecutedContext Properties

名称

类型

描述

ActionDescriptor

ActionDescriptor

动作方法的描述

Canceled

Bool

如果该动作被另1个过滤器取消,则返回true

Exception

Exception

返回由另1个过滤器或动作方法抛出的异常

ExceptionHandled

Bool

如果异常被处理返回true

Result

ActionResult

 

Result filter:

It manipulates the results produced by the action method


namespace System.Web.Mvc{

  //  Summary : Define the methods required for the result filter. 

  public interface IResultFilter{

    //  Summary : Called after the result of the operation is executed. 

    //  Parameter :filterContext:

    //    Filter context. 

    void OnResultExecuted(ResultExecutedContext filterContext);

    //  Summary : Called before the result of the operation is executed. 

    //  Parameter :filterContext:

    //    Filter context. 

    void OnResultExecuting(ResultExecutingContext filterContext);

  }

}

How an action method returns an action result enables the user to separate the intention of an action method from the execution of an action method. Applying a result filter to an action method calls OnResultExecuting when the action method returns a result, but before executing the action result. Call OnResultExecuted after the action result is executed

Built-in action filters and result filters

The Mvc framework contains a built-in class that can be used to create action filters and result filters. The name of this class is ActionFilterAttribute


public class CustomAuthAttribute:AuthorizeAttribute{

    /// <summary>

    ///  How to grant access to the request 

    /// </summary>

    /// <param name="httpContext"> Method of accessing requested information </param>

    protected override bool AuthorizeCore(HttpContextBase httpContext){

      return base.AuthorizeCore(httpContext);

    }

}
0

The only advantage of using this class is that there is no need to override and implement methods that are not intended to be used. In addition, there is no benefit in implementing the filter interface directly

Custom instance:


public class CustomAuthAttribute:AuthorizeAttribute{

    /// <summary>

    ///  How to grant access to the request 

    /// </summary>

    /// <param name="httpContext"> Method of accessing requested information </param>

    protected override bool AuthorizeCore(HttpContextBase httpContext){

      return base.AuthorizeCore(httpContext);

    }

}
1

Other filter properties:

public abstract class Controller : ControllerBase, IActionFilter, IAuthenticationFilter, IAuthorizationFilter, IDisposable, IExceptionFilter, IResultFilter, IAsyncController, IController, IAsyncManagerContainer

Several implementations of filters:

① Global filter

Register implementation classes directly in FilterConfig

② Implementation interface

③ Annotation

Sorting Filters

Filters are executed by type in their order: Authorization-"Action-" result. If there are unhandled exceptions, the framework executes exception filters at any 1 stage


public class CustomAuthAttribute:AuthorizeAttribute{

    /// <summary>

    ///  How to grant access to the request 

    /// </summary>

    /// <param name="httpContext"> Method of accessing requested information </param>

    protected override bool AuthorizeCore(HttpContextBase httpContext){

      return base.AuthorizeCore(httpContext);

    }

}
2

Built-in filter

过滤器

描述

RequireHttps

强迫Action使用Https协议

OutputCache

缓存1个Action的

ValidateInputand

ValidationAntiForgeryToken

与安全性有关的授权过滤器

AsyncTimeout

NoAsyncTimeout

用户异步控制器

ChildActionOnlyAttribute

1个支持Html.action和Html.RenderAction辅助器方法的过滤器

RequireHttps

The RequireHttps filter forces Action to use the HTTPS protocol. He redirects the user's browser to the same action, but uses the 'https://' protocol prefix

When an insecure request is formed, HandledNonHttpsRequest () is overridden to create custom behavior. The filter is only used for GET requests, and POST loses data; This filter is an authorization filter


Related articles: