Example of an MVC validation user login in asp.net

Source: Internet
Author: User

Therefore, I usually have to delete the acountcontroller of the relevant things, step by step to rebuild their own landing module.

MVC provides four kinds of filter (hooks) that we can do before or after the action, for example, to determine if there is a login, for example, to determine if there is permission.

Iauthorizationfilter: Execute before all filter and action execution

Iactionfilter: Executes before and after action is performed respectively.

Iresultfilter: respectively After action result execution and before

Iexceptionfilter: Executes only when filter, or action method, or action result throws an exception

Do login verification, with Iauthorizationfilter should be the best choice, such as the system with the landing and authorization, is to do with this. But what we are going to talk about today is how to use Actionfilter to do login verification.

When we go to the definition of controller, we find that this is true:

Public abstract class Controller:controllerbase, Iactionfilter, Iauthorizationfilter, IDisposable, Iexceptionfilter, Iresultfilter, Iasynccontroller, IController, Iasyncmanagercontainer

See the Iactionfilter interface out of the wood there, which lets us find a way: Create a new base class, overload the OnActionExecuting method in that class, and judge the permissions before all action execution:

The code is as follows Copy Code

public class Basecontroller:controller

{


Get:/base/


protected override void OnActionExecuting (ActionExecutingContext filtercontext)

{

if (filtercontext.httpcontext.request.cookies["UserID"] = = null)

{

if (this. routedata.values["Controller"]. ToString ()!= "Login")

{

Jump to landing page

Filtercontext.result = new Redirectresult ("/login/index");

}

}

Base. OnActionExecuting (Filtercontext);

}

}

As on the code by judging cookies in the UserID to determine whether the user landed, if not landing, jump to the Login/index. You will be able to make the judgment landing by inheriting all other controller that you need to verify your login from Basecontroller.

But Logincontroller can only directly inherit from controller, otherwise the program judge you did not login, and then jump to login, but before login to achieve index, the program judge you still did not log in, and then jump to login, realize a dead loop.

The following also provides a DLL that can be referenced directly, requiring the support of the. NET 4.0 framework.

Code:

The code is as follows Copy Code

Using SYSTEM.WEB.MVC;

Namespace System


{


<summary>


Attributes that require a user to log on to use


<para> If you do not need to process user logins, specify the Allowanonymousattribute property </para>


</summary>


[AttributeUsage (AttributeTargets.Method | AttributeTargets.Class, inherited = True, AllowMultiple = True)]


public class Authorizationattribute:filterattribute, Iauthorizationfilter


{


<summary>


Default constructor


</summary>


Public Authorizationattribute ()


{


String AuthUrl = system.configuration.configurationmanager.appsettings["AuthUrl"];


String Savekey = system.configuration.configurationmanager.appsettings["Authsavekey"];


String Savetype = system.configuration.configurationmanager.appsettings["Authsavetype"];

if (String.IsNullOrEmpty (AuthUrl))


{


This._authurl = "/user/login";


}


Else


{


This._authurl = AuthUrl;


}


if (String.IsNullOrEmpty (Savekey))


{


This._authsavekey = "Logineduser";


}


Else


{


This._authsavekey = Savekey;


}


if (String.IsNullOrEmpty (Savetype))


{


This._authsavetype = "session";


}


Else


{


This._authsavetype = Savetype;


}


}


<summary>


Constructor overload


</summary>


<param name= "loginurl" > indicates login address without login jump </param>


Public Authorizationattribute (String authurl)


: This ()


{


This._authurl = AuthUrl;


}


<summary>


Constructor overload


</summary>


<param name= "loginurl" > indicates login address without login jump </param>


<param name= "Savekey" > indicates the key name used to save login information </param>


Public Authorizationattribute (String authurl, String savekey)


: This (AuthUrl)


{


This._authsavekey = Savekey;


This._authsavetype = "session";


}


<summary>


Constructor overload


</summary>


<param name= "AuthUrl" > indicates login address without login jump </param>


<param name= "Savekey" > indicates the key name used to save login information </param>


<param name= "Savetype" > indicates how login is used to save login information </param>


Public Authorizationattribute (String authurl, String Savekey, String savetype)


: This (AuthUrl, Savekey)


{


This._authsavetype = Savetype;


}

Private String _authurl = String.Empty;


<summary>


Gets or sets a value that represents the login address


<para> if AuthUrl values are not defined in Web.config, the default is/user/login</para>


</summary>


Public String AuthUrl


{


get {return _authurl.trim ();}


Set


{


if (String.IsNullOrEmpty (value))


{


throw new ArgumentNullException ("The logon address used to authenticate user logon information cannot be empty!") ");


}


Else


{


_authurl = value. Trim ();


}


}


}

Private String _authsavekey = String.Empty;


<summary>


Gets or sets a value that represents the key name that the login uses to hold the login information


<para> if Authsavekey values are not defined in Web.config, the default is Logineduser</para>


</summary>


Public String Authsavekey


{


get {return _authsavekey.trim ();}


Set


{


if (String.IsNullOrEmpty (value))


{


throw new ArgumentNullException ("The key name used to save login information cannot be empty!") ");


}


Else


{


This._authsavekey = value. Trim ();


}


}


}

Private String _authsavetype = String.Empty;


<summary>


Gets or sets a value that represents how the login information is to be saved


<para> if authsavetype values are not defined in Web.config, the default is session save </para>


</summary>


Public String Authsavetype


{


get {return _authsavetype.trim (). ToUpper (); }


Set


{


if (String.IsNullOrEmpty (value))


{


throw new ArgumentNullException ("The way to save login information cannot be null, only" Cookie "or" session "!) ");


}


Else


{


_authsavetype = value. Trim ();


}


}


}

<summary>


Process User Login


</summary>


<param name= "Filtercontext" ></param>


public void Onauthorization (AuthorizationContext filtercontext)


{


if (Filtercontext.httpcontext = null)


{


throw new Exception ("This feature is only suitable for use by Web Applications!") ");


}


Else


{


Switch (authsavetype)


{


Case "Session":


if (filterContext.HttpContext.Session = null)


{


throw new Exception ("Server session not available!") ");


}


else if (!filtercontext.actiondescriptor.isdefined (typeof (Allowanonymousattribute), true)


&&!filtercontext.actiondescriptor.controllerdescriptor.isdefined (typeof (Allowanonymousattribute), true) )


{


if (filtercontext.httpcontext.session[_authsavekey] = = null)


{


Filtercontext.result = new Redirectresult (_authurl);


}


}


Break


Case "COOKIE":


if (!filtercontext.actiondescriptor.isdefined (typeof (Allowanonymousattribute), true)


&&!filtercontext.actiondescriptor.controllerdescriptor.isdefined (typeof (Allowanonymousattribute), true) )


{


if (filtercontext.httpcontext.request.cookies[_authsavekey] = = null)


{


Filtercontext.result = new Redirectresult (_authurl);


}


}


Break


Default


throw new ArgumentNullException ("The way to save login information cannot be null, only" Cookie "or" session "!) ");


}


}


}


}


}


Then add the following sentences to the Web.config file for configuring login authentication:


<appSettings>


<add key= "AuthUrl" value= "/user/login"/>


<add key= "Authsavekey" value= "Logineduser"/>


<add key= "Authsavetype" value= "Session"/>


</appSettings>


Use instance:


//... Omit reference


Namespace MrHuo.Framework.Blog


{


[authorization]//If you add this feature to controller, the method to access this controller will need to verify the user login status


public class Usercontroller:controller


{


[allowanonymous]//here is a special case with this feature, which means that this method does not need to verify user login status


Public ActionResult Index ()


{


//... Omit specific code


}


Here the method needs to verify the login status, the following similarities


Public ActionResult Create ()


{


//... Omit specific code


}


}


}

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.