ASP. NET MVC Learning---(ix) Permission filtering mechanism (end of article)

Source: Internet
Author: User

Believe in permission to filter big guys are not unfamiliar

When a user wants to access a page

First, the permission is judged and the corresponding processing action is performed.

In the WebForm

The most direct and primitive way is

Before all the code in the Page_Load event

Perform a method of permission judgment first

As for its professional competence mechanism here is no discussion

Students who want to know their own Google

Or click to enter:

WebForm Professional Authority authentication mechanism

So how do you implement permission validation in MVC?

As far as we know

In MVC, a method in the Controller class is requested based on the routing configuration.

There is no Page_Load method in WebForm.

Are we going to invoke a permission-judging method in every action method?

Obviously not possible = =

How could lazy handlers allow this to happen?

In fact, in the MVC framework

Provides a filter mechanism for programmers

Through the filter

We can control access as we wish.

So next

Educational Science Channel--approaching science takes you into the inner world of filters ~ ~


First, we can add a filter ourselves

To add a class named Myfilter1attribute

and inherit from the ActionFilterAttribute class (note that the ActionFilterAttribute namespace here is SYSTEM.WEB.MVC do not reference the wrong ~)

Now this myfilter1attribute is a filter class.

Because inheriting from the ActionFilterAttribute class

So the myfilter1attribute we added ourselves had some sort of filtering method.

Let's go to the definition of ActionFilterAttributeF12 and see what's inside.

As you can see, this actionfilterattribute is an attribute class (that's why people end up with attribute)

and implemented two very important interfaces Iactionfilter,iresultfilter

Let's go to the definition and see what's in these two interfaces.

Can see

Each of the two interfaces defines two methods, and since ActionFilterAttribute implements them, ActionFilterAttribute naturally has these four methods

So what are these four ways?

Announce now ~

As we said before, ActionFilterAttribute is actually an attribute class.

What is an attribute class?

For example, when the forward entity is validated, the label for the field of the entity is affixed

That tag is an attribute class.

Other words

Attribute classes can be used in the form of labeling

And the Myfilter1attribute we added ourselves is also an attribute class

What's the use of it?

Wait, you'll know.

Now rewrite the OnActionExecuting method in Myfilter1attribute

In fact, we can probably launch this method from the name of this method.

Yes, the method will call before the action method executes.

Conversely, another method in Iactionfilter--onactionexecuted is to call after the action method has finished executing

Accreditations

The following evidence:

public class Myfilter1attribute:actionfilterattribute    {        //This method calls public override void before the action method executes        OnActionExecuting (ActionExecutingContext filtercontext)        {            FilterContext.HttpContext.Response.Write (" I am onactionexecuting, I am in action method call Money Execution <br/> ");            Base. OnActionExecuting (Filtercontext);        }        The method calls public        override void OnActionExecuted (ActionExecutedContext filtercontext) After the action method executes        {            FilterContext.HttpContext.Response.Write ("I am onactionexecuted, I execute <br/> after the action method call");            Base. OnActionExecuted (Filtercontext);        }    }

Add an action method to the home controller

[MyFilter1]        public void Filtertest ()        {             Response.Write ("I am the action method, executed here ~~</br>");        }

Did you see it this time?

To use a filter in an action method

Just stick a filter label on the method ok~
The build runs with the following results:

A strong proof ~

But sometimes we have this kind of demand:

In the filter when you encounter the action method with a label labeled, skip the validation

What about this?

This easy operation can be done through the Filtercontext Actiondescriptor attribute class

Actiondescriptor as the name implies, the action method describes

In Actiondescriptor we can get the corresponding action method information, even get a controller to describe the Controllerdescriptor

The code is as follows:

The method calls public        override void OnActionExecuting (ActionExecutingContext filtercontext) before the action method executes        {            FilterContext.HttpContext.Response.Write ("I am onactionexecuting, I execute <br/> before action method call");            When judging the action method, there is a myfilter1attribute label            if (FilterContext.ActionDescriptor.IsDefined (typeof ( Myfilter1attribute) (false))            {                //If there is a direct return of Contentresult for the action method, the action method has a return value here, which is the equivalent of ending here. Will not be executed after the method, such as: onactionexecuted et                filtercontext.result = new Contentresult ();            }            Base. OnActionExecuting (Filtercontext);        }

Results

As you can see, the Response.Write in the action method and in onactionexecuted are not executed, that is, the action method is skipped


Before we used the method in the Iactionfilter interface

Next introduce the Iresultfilter interface method

Executes public        override void Onresultexecuting (ResultExecutingContext filtercontext) After the action method returns the result        {            FilterContext.HttpContext.Response.Write ("I am onactionexecuted, my action method returns results before executing <br/>");            Base. Onresultexecuting (Filtercontext);        }        Execute public        override void Onresultexecuted (ResultExecutedContext filtercontext) before the action method returns the result        {            FilterContext.HttpContext.Response.Write ("I am onresultexecuted, I execute <br/> after the action method returns the result");            Base. Onresultexecuted (Filtercontext);        }


There are also two methods in Iresultfilter

We will change the filtertest to the following code:

[MyFilter1]        Public ActionResult filtertest ()        {            Response.Write ("I am the Response.Write of the action method, executed ~~</br> here");            return View ();        }

and add the view as follows:

<body>    <div>        I'm Filtertest's view, where the action method is executed ~ ~    </div></body>

Build and run, result diagram:

As you can see, the difference between the method in the Iresultfilter interface and the Iactionfilter method is that the execution location is different

However, there is also a filter in the MVC framework

He's the Authority filter Authorizeattribute

This filter executes before all action method filters, that is, provides a method that can be validated in advance

We are adding a new filter class and inheriting from Authorizeattribute

Rewrite its Onauthorization method as follows:

It is important to note that the Onauthorization method of the base class is removed because we do not need it, and there may be some error exceptions.

public class Myfilter2attribute:authorizeattribute    {        //execute public override void before all action method filters        Onauthorization (AuthorizationContext filtercontext)        {            FilterContext.HttpContext.Response.Write (" I am onauthorization, execute <br/> "before all action method filters);            Base. Onauthorization (Filtercontext);        }    }
[MyFilter1]        [MyFilter2]        Public ActionResult filtertest ()        {            Response.Write ("I am the Response.Write of the action method, executed ~~</br> here");            return View ();        }

MyFilter2 Label for Filtertest method

Run:

There's evidence in the picture.

This

We can choose the right method to verify the permissions as needed.

But then there's a problem.

What's the problem?

This feature is affixed to the action method.

What if all the action methods in my controller have to be verified?

Does every action method stick to it?

What if all the action methods in all the controllers in my program need to be validated?

Rest assured ~

Lazy handlers are not going to do this stupid thing.

If all methods in a controller need to be validated

Then we can put the label on the controller class uniformly, as follows:

This way all the action methods in the controller will be validated

So what if each controller class has to be validated?

This time we need to open the App_start folder.

Have you seen a Filterconfig class?

Double hit Open FilterConfig.cs

We can then add global filters, such as:


Finally, we're introducing a filter for exception handling.

Add a filter class and inherit from Handleerrorattribute

public class Myfilter3attribute:handleerrorattribute    {        //Any exception that occurs anywhere in the program will execute public        override void Onexception (Exceptioncontext filtercontext)        {            //Get exception object            Exception ex = filtercontext.exception;            Logging error log            //directed friendly error interface            Filtercontext.result = new Redirectresult ("/home/index");            Important!! Tell the system that the exception has been handled!! Without this step, the system will still follow the normal exception handling process            filtercontext.exceptionhandled = true;            Base. Onexception (Filtercontext);        }    }


Note that the onexception of the base class here is not required.

So where does the exception-handling filter go?

It must be global.

Filters. ADD (New Myfilter3attribute ());

OK, get it done ~

Don't believe you run to see ~


An introduction to ASP. This is all over.

Looking forward to the next progress!




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.