. NET MVC Authorization filter,exception Filter and action filter

Source: Internet
Author: User

A: Knowledge point part

Permission is a knowledge point that is often involved in making a Web page, and you need to know the following knowledge when using MVC to design permissions:

The URL in MVC is executed according to the Controller->action->view page, but we often need to process some logic before the function executes the specified action or after the action method, in order to handle the logic, the ASP. MVC allows you to create an action filter filter, and we all know that each [Attribute] used on the action is a custom filter.

MVC provides four types of filter interfaces: Iactionfilter,iauthorizationfilter,iexceptionfilter,iresultfilter, these four kinds of filter are sufficient to meet the functions we want to implement, It also provides several current

Filter:outputcacheattribute, Handleerrorattribute, and authorizeattribute that can be used. (Authorizeattribute and Handleerrorattribute inherit from FilterAttribute Class)


Iactionfilter provides two methods: onactionexecuting is called before invoking an action method. onactionexecuted called after the action method is called.

Iresultfilter provides two methods:onresultexecuting is called before executing the result of the operation returned by the action method. onresultexecuted is called after executing the result of the operation returned by the action method.

Iauthorizationfilter is a filter that is used for authentication. Only one void Onauthorization (AuthorizationContext Filtercontext) method is provided.

Iexceptionfilter will be called in the event of an exception, and is a method that only provides a void Onexception (Exceptioncontext filtercontext);

The method execution order of the 4 interfaces is as follows: Iauthorizationfilter-Iactionfilter->iresultfilter->iexceptionfilter

The ActionExecutedContext class contains a canceled property that allows you to cancel the current Action "

Now let's take a look at one of the most used classes ActionFilterAttribute:

His inheritance hierarchy is


 Public Abstract class Actionfilterattribute:filterattribute, Iactionfilter, iresultfilter{
He inherited the FilterAttribute, Iactionfilter, iresultfilter three classes, usually we need to deal with some functions before the action logic, such as permissions, so we will customize a filter, which inherits from
ActionFilterAttribute, and then ActionFilterAttribute the function that is inherited by the interface Iactionfilter, Iresultfilter
void onactionexecuting (actionexecutingcontext filtercontext)
void onactionexecuted (ActionExecutedContext filtercontext)
void Onresultexecuting (ResultExecutingContext filtercontext)

Where ActionFilterAttribute has two attributes, one is inherited FilterAttribute, the other Inherits attribute

Order Gets or sets the sequence in which the action filter is executed. (inherited from FilterAttribute.) )

TypeId when implemented in a derived class, gets the unique identifier of the Attribute. (inherited from Attribute.) )

For example, the following code snippet:

[Orderfilter (roleid="2", Order=2 )]
[Userfilter (UserId="3", Order=1 )]
Public ActionResult Test () {
return View ();

The order in which the program executes is: userfilter->orderfilter->test

Two: Example part

after learning some of the above, let's look at the privilege instances I've designed:
If you do not know the user, role, group, permissions before some of the relationship, I suggest you first read my previous "Basic knowledge of permissions", this article is I turned around, I feel good, because before I finished the project did not
The points are clear, nowafter reading that article, the seat, it is clear that I was also in accordance with the user, role, group, authority and other these relationships to carry out ^_^ (if the following the wrong, please correct)
Suppose you now have 4 functional permissions: Add features, delete features, publish features, modify features, and more. Designed in binary 01 format, 0 means no permissions for the feature, and 1 indicates that the permission is
in other words, in order
Add Delete publication modifications
1 1 1 1 If only the modification function is 0001,
If you have add and remove functions that are 1100,

convert binary to int number add function: (1000=int number 8) Delete function: (0100=int number 4) Release function: (0010=int number 2) Modify function: (0001 =int number 1)
that I can understand as-----permissions
and each user has the function (permission) is not the same, can have a variety of combinations, such as 1001 (add and Modify permissions) 0011 (publish and Modify permissions) 1111 (full permission)
that I can understand as-------group
for different users, I changed their privilege combination to an int number in the permission (int) field of the user table, so that: (Add and Modify permissions 1001=int number 9)
(Release and Modify permissions 0011=int number 3) (Total permissions 1111=int number of all)
that I can understand as--------role
As for the user is our own database inside the username.

Set user permissions: Simply add the int number of the function permission to the database;
To View user permissions: You need to resolve the int value of the permission to a binary number, then the int value of the 1 digits and the corresponding function value.
implementation: When the user logs in, the first view of his permission int (that is, the role), the role resolves to the appropriate group, the permissions of each set of int value loaded into the user principal's roles, he is an array form.
(because there is one or more function permissions)
then add a custom filter to each action that requires permission filtering: that is, within the overloaded OnActionExecuting method, to determine whether the function permission exists in the current user's roles, and if so,
Then go to the page, or skip to the No Permissions page.

Here is the code, inheriting the ActionFilterAttribute class, and overloading the onactionexecuting method:

 PublicclassRolefilter:actionfilterattribute {
PublicstringCheckrole {Get; Set; } //function permission values that should be passed in
PublicOverridevoidonactionexecuting (ActionExecutingContext filtercontext) {
if(!string. IsNullOrEmpty (Checkrole)) {
if(!filterContext.HttpContext.User.Identity.IsAuthenticated) {//determine if the user is logged in, not logged in to the login page,
stringRedirectURL=string. Format ("? RETURNURL={0}", Okurl);
Filtercontext.result=NewRedirectresult (loginurl);
} Else { //logged in user
BOOLisauthorize=FilterContext.HttpContext.User.IsInRole (Checkrole);
if(!isauthorize)//to determine if the user has Checkrole permissions, skip to the Permissions error page.
Filtercontext.result=NewRedirecttorouteresult ("Default", NewRouteValueDictionary (New{Controller=" Account", Action="Authorizeerror" }));
} Else {
ThrowNewInvalidOperationException ("the user does not specify a role, please contact the administrator to give the role. ");

Read the permissions of the user role as soon as the program is started. To do the above comparison:
   public   mvcapplication () {
AuthorizeRequest + = new EventHandler (mvcapplication_authorizerequest);

void mvcapplication_authorizerequest ( object sender, EventArgs e) {
// get the role of the current user
if (httpconte Xt. Current.User.Identity.IsAuthenticated) {
///The following method converts a role (int) to binary and then calculates an array of int values for each permission
var ro Les = CMSPermissionController.Instance.PermissionIdList ( HttpContext.Current.User.Identity.Name.Trim ()). ToArray < string ; ();
HttpContext.Current.User = new System.Security.Principal.GenericPrincipal ( HttpContext.Current.User.Identity, roles);

The procedure to invoke is:

// You can also add "attribute" to the entire controller as needed .
= " 2 " )]
Public class Groupcontroller:controller {
Public ActionResult Index () {
return View ();

Public ActionResult Create () {
return View ();

// You can also add a specific action to a
= " 4 " )]
Public string Delete (string relapath) {
// To do ...

The above code basically can be implemented, in the course of debugging, there was a colleague asked, if I want to check on the delete checkrole= "8" When you do, I was a bit of a Meng ... Didn't think
Too much, I think that is the first checkrole is 4 or first checkrole is "8", it seems that there is no such situation, because I define the 4,8 and other numbers, itself is the right to death, such as
Add delete publish modify the corresponding permission number is 8,4,2,1; So if we're going to delete the permission to be 4, to check the added permissions 8, the business logic itself does not exist! O (∩_∩) o

Original from http://www.cnblogs.com/Joans/archive/2011/07/20/2110775.html

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.