ASP. NET MVC Learning Filter article (1)

Source: Internet
Author: User
Tags httpcontext

Http://www.cnblogs.com/yaozhenfa/p/asp_net_mvc_filter_1.html

I. Preface

Following the four previous essays on ASP. NET MVC , we continue to learn. In the previous section we learned about the use of controllers, and in this section we will learn how to use filters to control user access to pages.

Two. Text

The following example builds on ASP. NET MVC 4 (VS2012)

1. Authorization Filter

As long as the user's site is involved, it will certainly involve what permissions users can access to which page. For beginners, it is possible to write this function individually on each page, and the result is a lot of repetitive code, which is not convenient for future changes. After a certain experience, you will use a centralized control approach, so that all pages first to perform a specific method to judge, the advantage is to reduce the duplication of code, but also flexible configuration. But for some of the special needs of the page is a bit of a force can not, and this authority to judge the code will be mixed with the logic code of the page, difficult to distinguish. The authorization filter introduced today is a way to control each action with annotation attributes, and it can be configured flexibly.

First we create a new Filter folder in the Web site root, where we create a new Custauthorizeattribute class in which the specific code in the class is as follows :

1 namespace Mvcstudy.filter 2 {3 Public     class Custauthorizeattribute:authorizeattribute 4     {5         private Strin g[] roles; 6  7 public         Custauthorizeattribute (params string[] role) 8         {9             roles = role;10         }11         override bool Authorizecore (HttpContextBase HttpContext) (             String role = httpcontext.request.querystring["Role"];15             if (role! = null)             -{                 roles return. Contains (role);             }19             return base. Authorizecore (HttpContext);         }21     }22}

We know from the above code that this filter will require the user to pass in the accessible role when it is used, which is ultimately the Authorizecore method, which is responsible for judging the current request to have permissions, here we are to demonstrate, So it is directly judged by the value of the role of the query string.

Now that we have the filter, let's create a new home controller and create a new Home folder under the views, and create a new name Index under the Home folder. and a view of the List . Then we open the Home controller.

in which the following code is written :

1 namespace mvcstudy.controllers 2 {3 Public     class Homecontroller:controller 4     {5         [Custauthorize ("VIP") ] 6 Public         ActionResult Index () 7         {8             return View (); 9         }10         [Custauthorize ("admin")]12 Public         ActionResult List ()         {             return View ();         }16     }17}

We can see that the author has defined the Index action as only role for VIP access, and List is admin. Then we run the project, the browser will open http://localhost:7575/by default (the port depends on the actual situation), but you will find that you will be transferred to Http://localhost:7575/Account/Login? RETURNURL=%2F This page, because we did not create this view in the project, so we will report 404 errors. And this is the default behavior of ASP . NET MVC, of course, we can change this behavior, let's change this behavior, so that it jumps directly to the Login view, modifies Custauthorizeattribute class.

The code looks like this:

1 namespace Mvcstudy.filter 2 {3 Public     class Custauthorizeattribute:authorizeattribute 4     {5         private Strin g[] roles; 6  7 public         Custauthorizeattribute (params string[] role) 8         {9             roles = role;10         }11         override bool Authorizecore (HttpContextBase HttpContext) (             String role = httpcontext.request.querystring["Role"];15             if (role! = null)             -{                 roles return. Contains (role);             }19             return base. Authorizecore (HttpContext),         }21         protected override void Handleunauthorizedrequest ( AuthorizationContext filtercontext)         {             urlhelper url = new Urlhelper (filtercontext.requestcontext); 25             Filtercontext.result = new Redirectresult ("/login");     }28}

The key is that we rewrite the handleunauthorizedrequest method, which is only called if the authorizecore returns false . At the same time, there is a result property in the parameter of the method that assigns the final processing result to it.

Recompile, we continue to access the default path, this time we can find that the transfer path has become http://localhost:7575/Login, here we can handle the situation of authorization failure, and now we are going to start testing a few correct results first is Index, we only need to access the path to HTTP://LOCALHOST:7575/HOME/INDEX?ROLE=VIP (same as HTTP://LOCALHOST:7575/?ROLE=VIP), if you want to access the list, We need to access this path http://localhost:7575/Home/List?role=admin, and with this simple example, we can see how the user's access to the page is controlled in ASP.

2. Exception filter

In our development process, we have a lot of time to modify the exception to prevent the occurrence of the exception. But in the actual operation there will always be a lot of problems we have not found, as well as other malicious attacks. This time we need a unified mechanism to control and deal with these anomalies, perhaps I say a lot of people will associate with the try{}catch{}, it is true that the exception of the capture is with them, but you have not thought, if a website is flooded with try{} catch{}, not only not beautiful, but also to control. and ASP . NET MVC provides us with an exception filter that allows you to add this annotation attribute to each action so that we can control and handle these exceptions flexibly.

First we create a new Custexceptionattribute class in the Filter file and write the following code in it:

1 namespace Mvcstudy.filter 2 {3 Public     class Custexceptionattribute:filterattribute, Iexceptionfilter 4     {5
   public void Onexception (Exceptioncontext filtercontext) 6         {7             if (!filtercontext.exceptionhandled) 8             { 9                 Filtercontext.result = new Redirectresult ("error.html");                 filtercontext.exceptionhandled = true;11             }12         }13     }14}

We can see here that we still use result to assign the result of our processing to it, but here we also judge the exceptionhandled property, The meaning of this property is that if other exception filters have already handled the exception, the value of this property is true, in order to be able to adapt to the large range, so I suggest that the reader should also first determine whether there are other exception filters have already handled the exception.

Below we use the Index action in the Home Controller:

1 namespace mvcstudy.controllers 2 {3 Public     class Homecontroller:controller 4     {5         [Custexception ()] 6         Public ActionResult Index () 7         {8             throw new NullReferenceException (); 9             return View ();         }11     } 12}

This time we visit http://localhost:7575/will jump to http://localhost:7575/ Error.html page (because the author does not build this page so it will show 404), but the reader can see here I just jump to a specific page based on the exception, in fact, ASP. NET MVC has already implemented this annotation property by default, This annotation property is the HandleError class, and we only need to pass in the type of exception that needs to be caught, and the corresponding page.

Here we modify the Home Controller's Index action:

1 namespace mvcstudy.controllers 2 {3 Public     class Homecontroller:controller 4     {5         [HandleError (Exceptiont Ype=typeof (NullReferenceException), view= "error")] 6 public         ActionResult Index () 7         {8             throw new NullReferenceException (); 9             return View ();         }11     }12}

Then we recompile and visit the page and find that the page did not jump to a specific page as we intended, but instead showed the error details directly. This is because ASP . NET MVC does not turn on custom exception handling by default, so this default page appears, and below we modify the Web. configto add the following configuration :

At this point we recompile the page, but we will find that the page will have content, because this page calls the views/shared/error.cshtml page.

Not to be continued ...

ASP. NET MVC Learning Filter article (1)

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.