ASP. Net mvc4

Time:2022-1-12

Filters in mvc4

The filter injects additional logic into the MVC framework’s request processing. Cross focus is realized.

Cross focus: a function that is used for the entire application and is not suitable for a local location.

The filter is Net, which adds additional steps to the request processing pipeline.

Annotation properties are derived from system Attribute is special Net class.

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

Basic types of filters:

Filter type

Interface

Default implementation

describe

Authorization

IAuthorizationFilter

AuthorizationAttribute

First run

Action

IActionFilter

ActionFilterAttribute

Run before and after action method

Result

IResultFilter

ActionResultAttribute

Before and after the action result is executed

Exception

IExceptionFilter

HandlerErrorAttribute

Only when the filter and action are abnormal

Authorization filter: iauthorizationfilter

namespace System.Web.Mvc{

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

  public interface IAuthorizationFilter{

    //Absrtact: called when authorization is required.

    //Parameter: filtercontext: filter context.

    void OnAuthorization(AuthorizationContext filterContext);

  }

}

be careful:

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

public class CustomAuthAttribute:AuthorizeAttribute{

    /// <summary>

    ///Whether to grant access to the request

    /// </summary>

    ///< param name = "httpcontext" > method for accessing request information < / param >

    protected override bool AuthorizeCore(HttpContextBase httpContext){

      return base.AuthorizeCore(httpContext);

    }

}

The main reason for directly implementing the iauthorizationfilter interface is to obtain access to the authorizationcontext passed to onauthorization(), through which you can obtain more extensive information (routing details, current controller and action method information). Using the interface not only has security risks, but also makes the logic established in the authorization annotation attribute closely coupled with the controller, which destroys the separation of concerns and is not easy to maintain.

Built in authorization filter:

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

When authorizeattribute is used directly, its public attribute can be used to specify the authorization policy

Authorizeattribute attribute

name

type

describe

Users

String

A comma separated list of user names that specify the action methods that these users can access

Roles

String

A comma separated list of roles. Users must have at least one role


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{

    //Absrtact: called when an exception occurs.

    //Parameter: filtercontext:

    //Filter context.

    void OnException(ExceptionContext filterContext);

  }

}

Onexception () is called when an unhandled exception occurs. The parameter of this method is an exceptioncontext object, which is derived from controllercontext and provides many useful properties.

name

type

describe

Controller

ControllerBase

Returns the requested controller object

HttpContext

HttpContextBase

Provides access to request details and responses

IsChildAction

Bool

If it is done automatically, it returns true

RequestContext

RequestContext

Provides access to httpcontext and routing data

RouteData

RouteData

Returns the requested routing data

Properties inherited from controllercontext

name

type

describe

ActionDescripter

ActionDescripter

Provide details of the action method

Result

ActionResult

Used for the result of the action method. The request can be cancelled through a non null value

Exception

Exception

Unhandled exception

ExceptionHandled

Bool

Returns true if another filter has marked the exception as handled

Implement custom exception filters


public class RangeExceptionAttribute : FilterAttribute, IExceptionFilter{

    public void OnException(ExceptionContext filterContext){

}

}

Use the built-in exception filter:

Handleerrorattribute attribute

name

type

describe

ExceptionType

Type

The type of exception handled by the filter

View

String

The name of the view template that this filter renders

Master

String

The layout name used when rendering the view of this filter

preparation:

On the web The handleerrorattribute filter takes effect only when the custom error is enabled in the config file. In < system Add a customErrors attribute to the web > node;

<system.web>

 <!-- Custom error page AA html-->

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

 </system.web>

The default value of the mode attribute is remoteonly. During development, the handleerrorattribute will not intercept exceptions, but the handleerrorattribute takes effect when the application is deployed to the product server and requests from another computer


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

    public ActionResult Index(){

      return View();

  }

When rendering a view, the handleerorattribute filter passes a handleerorinfo view model object, which is a wrapper that encapsulates the exception details

name

type

describe

ActionName

String

Returns the name of the action that generated the exception

ControllerName

String

Returns the name of the controller that generated the exception

Exception

Exception

Return this 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: model must be included when using handleerror filter Exception. Stacktrace otherwise, the view will not be displayed to the user, and the reference does not need to show the stack information to the user, so you can put the value into div and hide it

Action filter

Multipurpose filter for any purpose

namespace System.Web.Mvc{

  //Summary: defines the method used in the action filter.

  public interface IActionFilter{

    // Abstract: after executing the operation method, call.

    //Parameter: filtercontext:

    //Filter context.

    void OnActionExecuted(ActionExecutedContext filterContext);

    // Abstract: before executing the operation method.

    //Parameter: filtercontext:

    //Filter context.

    void OnActionExecuting(ActionExecutingContext filterContext);

  }

}

Actionexecutingcontext property

name

type

describe

ActionDescriptor

ActionDescriptor

Description of action method

Result

ActionResult

As a result of the action method, the filter can cancel the request if the attribute is set to a non null value

Actionexecutedcontext property

name

type

describe

ActionDescriptor

ActionDescriptor

Description of action method

Canceled

Bool

Returns true if the action is cancelled by another filter

Exception

Exception

Returns an exception thrown by another filter or action method

ExceptionHandled

Bool

Returns true if the exception is handled

Result

ActionResult

 

Result filter:

It operates on the results of the action method

namespace System.Web.Mvc{

  //Summary: defines the method required for the result filter.

  public interface IResultFilter{

    // Abstract: after the operation result is executed, it is called.

    //Parameter: filtercontext:

    //Filter context.

    void OnResultExecuted(ResultExecutedContext filterContext);

    // Abstract: before the operation result is executed.

    //Parameter: filtercontext:

    //Filter context.

    void OnResultExecuting(ResultExecutingContext filterContext);

  }

}

How the action method returns the action result enables the user to separate the intention of the action method from the execution of the action method. When the result filter is applied to an action method, it will return the result when the action method returns, but call OnResultExecuting before executing the result of the action. After the execution of the action result, call OnResultExecuted.

Built in action filter and result filter

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

namespace System.Web.Mvc{

  //Summary: represents the base class of the filter attribute.

  public abstract class ActionFilterAttribute : FilterAttribute, IActionFilter, IResultFilter{

    //Absrtact: after executing the operation method, ASP Net MVC framework call.

    //Parameter: filtercontext:

    //Filter context.

    public virtual void OnActionExecuted(ActionExecutedContext filterContext);

    //Absrtact: before executing the operation method, ASP Net MVC framework call.

    //Parameter: filtercontext:

    //Filter context.

    public virtual void OnActionExecuting(ActionExecutingContext filterContext);

    //Absrtact: after executing the operation result, ASP Net MVC framework call.

    //Parameter: filtercontext:

    //Filter context.

    public virtual void OnResultExecuted(ResultExecutedContext filterContext);

    //Absrtact: before executing the operation result, ASP Net MVC framework call.

    //Parameter: filtercontext:

    //Filter context.

    public virtual void OnResultExecuting(ResultExecutingContext filterContext);

  }

}

The only advantage of using this class is that you don’t need to rewrite and implement methods you don’t intend to use. In addition, there is no benefit in implementing the filter interface directly

Custom instance:


public class ProfileAllAttribute: ActionFilterAttribute{

    private Stopwatch timer;

    public override void OnActionExecuting(ActionExecutingContext filterContext){

      timer = Stopwatch.StartNew();

    }

 

    public override void OnActionExecuted(ActionExecutedContext filterContext){

      timer.Stop();

      filterContext.HttpContext.Response.Write(

        string.Format("<div>Total elapsed time:{0}</div>", timer.Elapsed.TotalSeconds));

    }

}

public class HomeController : Controller{

    [ProfileAll]

    public ActionResult Index(){ return View();}

}

Other filter properties:

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

Several implementations of filters:

① Global filter

Directly register the implementation class in filterconfig

② Implementation interface

③ Annotation

Sort filters

Filters are executed by type in the order of authorization – action – result. If there are unhandled exceptions, the framework executes exception filters at any stage

namespace System.Web.Mvc

{

  //Absrtact: represents the base class of action and result filter attributes.

  public abstract class FilterAttribute : Attribute, IMvcFilter{

    //Summary: gets or sets a value indicating whether multiple instances of a filter attribute can be specified.

    //Return result: true if multiple instances of the filter feature can be specified; Otherwise, it is false.

    public bool AllowMultiple { get; }

    //Summary: gets or sets the order in which the action filter is executed.

    //Return result: the order in which the action filter is executed.

    public int Order { get; set; }

  }

 
}

Built in filter

filter

describe

RequireHttps

Force action to use HTTPS protocol

OutputCache

Cache an action

ValidateInputand

ValidationAntiForgeryToken

Security related authorization filters

AsyncTimeout

NoAsyncTimeout

User asynchronous controller

ChildActionOnlyAttribute

One supports HTML Action and HTML Filter for renderaction helper method

 

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 unsafe request is formed, override handlednonhttpsrequest() to create a custom behavior. This filter is only used for get requests, and post will lose data; This filter is an authorization filter

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support developpaer.