MVC Filter Detailed

Source: Internet
Author: User
Tags httpcontext stack trace types of filters

Every request in Aps.net MVC (hereinafter referred to as "MVC") is assigned to the appropriate controller and corresponding behavior method to be processed, and in the back and forth of these processing, if you want to add some additional logic processing. The filter is used at this time.

There are four types of filters supported by MVC: Authorization (Authorization), Action (behavior), result (result), and exception (exception). As shown in the table below,

Filter type

Interface

Describe

Authorization

Iauthorizationfilter

This type (or filter) is used to restrict access to a behavior method of the controller or controller

Exception

Iexceptionfilter

Used to specify a behavior that the specified behavior handles a behavior method or an exception thrown in a controller

Action

Iactionfilter

Processing before or after entering a behavior

Result

Iresultfilter

Used to return the previous or subsequent processing of the result

However, there are only three filters implemented by default, authorize (authorization), Actionfilter,handleerror (error handling), and various information as shown in the following table

Filter filters

Class name

Implementing interfaces

Describe

Actionfilter

Authorizeattribute

Iauthorizationfilter

This type (or filter) is used to restrict access to a behavior method of the controller or controller

HandleError

Handleerrorattribute

Iexceptionfilter

Used to specify a behavior that the specified behavior handles a behavior method or an exception thrown in a controller

Custom

ActionFilterAttribute

Iactionfilter and Iresultfilter

Handling before or after processing or returning results before or after entering the behavior

The filter described below, in addition to the above several, but also add a filter outputcache

1 Authorization Filter Authorize

1.1 Default authorize use

Now on the Internet, whether it is required to verify the location of more than, e-mail, shopping, and sometimes even spit a slot to be prompted to sign in. Some of the operations here are permitted only if the authorization is authenticated. In MVC, authorize can be used to implement. For example, a simple password change operation

        [Authorize]        Public ActionResult ChangePassword ()        {            return View ();        }

It requires the user to pass the authorization to enter into this behavior method, otherwise hard to request that page, will only get this result

If you want to pass authentication, by calling the Formsauthentication.setauthcookie method to get authorization, the landing page is as follows

@model filtertest.models.loginmodel@{    Layout = null;} <! DOCTYPE html>

Behavioral methods are as follows

        [httppost]//here uses the predicate filter, which only handles the POST request public        ActionResult Login (Loginmodel login)        {            if (login. UserName = = "Admin" && login. Password = = "123456")            {                Formsauthentication.setauthcookie (login. UserName, false);                Return Redirect ("/customer/changepassword");            }            return View ();        }

Of course, there must be logged off, because the logout is in the login after the occurrence, no login success is not logged out, so the behavior of the logoff method also add authorize filter, logout call is the FormsAuthentication.SignOut method, the code is as follows

        [Authorize]        Public ActionResult LogOut ()        {            formsauthentication.signout ();            Return Redirect ("/customer/login");        }

1.2 Custom Authorization

We do not have to use the MVC default authorize authorization validation rules, rules can be self-defined, custom authorization filter can inherit Authorizeattribute this class, there are two methods in this class is to be rewritten

    • BOOL Authorizecore (HttpContextBase HttpContext): Here is the logical processing of authorization validation, which returns true by authorization and returns False if not.
    • void Handleunauthorizedrequest (AuthorizationContext filtercontext): This method is a matter of handling authorization failures.

This defines a comparison of the ride of the authorization processor, when the request is just an even minute, the authorization can be obtained, and vice versa. When the authorization fails, it jumps to the landing page.

    public class Myauthorizeattribute:authorizeattribute    {                protected override bool Authorizecore ( HttpContextBase HttpContext)        {            //return base. Authorizecore (HttpContext);            return DateTime.Now.Minute% 2 = = 0        }                protected override void Handleunauthorizedrequest (AuthorizationContext Filtercontext)        {            filterContext.HttpContext.Response.Redirect ("/customer/login");                        Base. Handleunauthorizedrequest (Filtercontext);        }    }

And then using a behavioral method,

        [Myauthorize]        Public ActionResult ShowDetail ()        {            return View ();        }

The ShowDetail view can be accessed whenever even minutes, otherwise it will jump to the landing page.

2 Handling Error Filter HandleError

2.1 Default HandleError Use

In the usual development, think of exception handling immediately think of try/catch/finally statement block. In the case of MVC, if something is thrown in the behavior method, and the behavior method or controller is useful on HandleError filter, the abnormal information will be displayed in a certain view, the view that shows the exception information is Views/shared/error

The properties of this handleerror are as follows

Property name

Type

Description

Exceptiontype

Type

The type of exception to handle, equivalent to the type of catch catch in the Try/catch statement block, If this is not filled in, then all exceptions are handled

View

< p>string

Specifies the view that needs to show the exception information, just need the view name, this view file will be placed in the Views/shared folder

Master

String

Specifies the name of the master view to use

Order

Int

Specifies the order in which the filters are applied, default is-1, and the highest priority is-1

This order property is actually not just the HandleError filter, its precedence rules are the same as other filters.

Here's a deliberate way to throw an abnormal behavior.

        [HandleError (Exceptiontype = typeof (Exception))]        Public ActionResult Throwerrorlogin ()        {            throw new Exception ("This is throwerrorlogin Action throw");        }

It's not enough, just add the following code to the <system.web> section in the Web. config file

<customerrors mode= "on"/>

Because it is closed in the default development mode, it will not open until it is deployed to the server, allowing the exception information to be displayed in a friendly view.

As you access the Throwerrorlogin view here, you go to a specific view because it was thrown once.

The exception view we see here is that, in addition to the exception view generated by default when the project is built, we can define the exception view ourselves, the exception information to be used in the view, which can be obtained by @model, which is an instance of the Exceptioninfo type. For example, an exception view was created as follows

@{    Layout = null;} <! DOCTYPE html>

It stores the path is inside the ~/views/shared, like the above behavior method if you want to use the exception information to render to this view, the controller is changed to this can be

[HandleError (Exceptiontype = typeof (Exception), View = "Myerrorpage")]

2.2 Custom Error exception handling

The error-handling filter here can also be defined by itself, by inheriting the Handleerrorattribute class, overriding the void Onexception (Exceptioncontext filtercontext) method, This method is called to handle unhandled exceptions, such as

        public override void Onexception (Exceptioncontext filtercontext)        {            //base. Onexception (filtercontext);            if (!filtercontext.exceptionhandled &&                 filterContext.Exception.Message = = "This is Throwerrorlogin Action Throw ")            {                 filtercontext.exceptionhandled=true;                FilterContext.HttpContext.Response.Write ("5 washes ten No problem<br/>" +                    filterContext.Exception.ToString ());            }        }

Here is used to pass in a Exceptioncontext object, both can get the requested information from it, but also can get the information of the exception, it is some of the properties are as follows

Property name Type Describe
Actiondescriptor Actiondescriptor Provides detailed methods of operation
Result ActionResult The result of the action method, the filter can be canceled, required to set this property to a non-null value
Exception Exception Unhandled exception
Exceptionhandled bool Another filter that returns true if there is significant exception handling


The Exceptionhandler property here is to mention that if this exception is processed, set it to true, then even if there are other error handlers to catch the exception, you can also use the Exceptionhandler property to determine whether the exception has been handled, Avoid repeating an exception and cause a new problem.

3 OutputCache Filter

The OutputCache filter is used as a cache, saving the user time and resources to access the application to improve the user experience, but this I tried to test out its effect. Leave your notes for a minute. Outputcacheattribute This class has the following properties

Property name

Type

Describe

Duration

Int

The cache time, in seconds, can theoretically be long, but in fact, when the system resources are tight, the cache space will be recovered by the system.

VaryByParam

String

Which field is used to cache the data, such as when the "id" field changes, you need to change the cache (still retain the original cache), then you should set VaryByParam to "id". Here you can set the following values:
* = Change the cache when any parameter changes.
None = does not change the cache.
With a semicolon ";" The list of field names for the interval = changes in the field in the table, the cache is changed.

Location

OutputCacheLocation

Where the cached data is placed. The default is any, and the other values are client,downstream,server,none,serverandclient

Nostore

bool

A level Two store that determines whether sensitive information is blocked.

For example, a outputcache filter can be used like this

        [OutputCache (location= system.web.ui.outputcachelocation.client,duration=60)]        Public ActionResult Login ()        {            return View ();        }

Or there's another way to use it--using a configuration file, add the following settings under the <system.web> node

    <caching>      <outputCacheSettings>        <outputCacheProfiles>          <add name= "Testcache" location= "Client" duration= "/>"        </outputCacheProfiles>      </outputCacheSettings>    </caching>

That's when you use control.

        [OutputCache (cacheprofile= "Testcache")]        Public ActionResult Login ()        {            return View ();        }

4 Custom Filters

This custom filter should be useful in the event that the filter described earlier does not meet the requirements and defines its own processing logic in the back and forth of the behavior method execution. To customize a filter, you inherit the ActionFilterAttribute class, which is an abstract class that implements the Iactionfilter and Iresultfilter interfaces. Mainly by rewriting four virtual methods to achieve before and after the behavior method execution and return of the injection logic

Method

Parameters

Describe

OnActionExecuting

ActionExecutingContext

Execute before the behavior method executes

onactionexecuted

ActionExecutedContext

Executes after the behavior method executes

Onresultexecuting

ResultExecutingContext

Executes before the behavior method returns

onresultexecuted

ResultExecutedContext

Executes after the behavior method returns

The four method execution order is onactionexecuting-->onactionexecuted-->onresultexecuting-->onresultexecuted. The parameters of the above four methods are inherited from the base Contollorcontext class. For example, a custom filter is defined below

   public class Mycustomerfilterattribute:actionfilterattribute {public string Message {get; set;} public override void OnActionExecuted (ActionExecutedContext filtercontext) {base.            OnActionExecuted (Filtercontext); FilterContext.HttpContext.Response.Write (String.        Format ("<br/> {0} Action finish Execute ...", Message)); } public override void OnActionExecuting (ActionExecutingContext filtercontext) {checkmessage (fil            Tercontext); FilterContext.HttpContext.Response.Write (String.            Format ("<br/> {0} Action start Execute ...", Message)); Base.        OnActionExecuting (Filtercontext); } public override void Onresultexecuted (ResultExecutedContext filtercontext) {filtercontext.http Context.Response.Write (String.            Format ("<br/> {0} Action finish Result ...", Message)); Base.        Onresultexecuted (Filtercontext); } public override void ONresultexecuting (ResultExecutingContext filtercontext) {filterContext.HttpContext.Response.Write (string .            Format ("<br/> {0} Action start Execute ...", Message)); Base.        Onresultexecuting (Filtercontext); private void Checkmessage (ActionExecutingContext filtercontext) {if (string. IsNullOrEmpty (Message) | | String. Isnullorwhitespace (message)) Message = FilterContext.Controller.GetType ().        Name + "' s" + filterContext.ActionDescriptor.ActionName; }    }

The behavior method that uses it is defined as follows

        [Mycustomerfilter]        Public ActionResult customerfiltertest ()        {            Response.Write ("<br/>invking customerfiltertest Action");            return View ();        }

Execution results are as follows

This proves the order in which it was said.

When the controller is also using this filter, and the behavior method is not used, the result is as follows

If both the controller and the Behavior method use filters, it is theoretically possible to display the organic combination of the above two results. But not really, because there is a feature missing when defining the filter: [AttributeUsage (AttributeTargets.All, AllowMultiple = True)], Add this to the Mycustomerfilterattribute on the line.

    [AttributeUsage (AttributeTargets.All, AllowMultiple = true)]//multiple calls to public    class Mycustomerfilterattribute: ActionFilterAttribute    {        ...    }

As can be seen from this graph, the same filter is used in the controller and the behavior method, the same method will be executed in order, if the default value (without order), the general order is the outermost to the innermost, that is, "global"-"controller"--"behavior method" And, in particular, the error-handling filter, because the exception is thrown out of the inside, so its order is also reversed: "Behavior method"-"controller"--"global".

Since there is a global filter, the global filter is set in the Registerglobalfilters (globalfiltercollection filters) in the Global.asax file.

public static void Registerglobalfilters (Globalfiltercollection filters)        {            filters. ADD (New Handleerrorattribute ());            Filters. ADD (New Myfilters.mycustomerfilterattribute () {message= "global"});//Global Filter        }

Here it also adds an error-handling filter to handle exceptions thrown by the entire MVC application.

MVC Filter Detailed

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.