ASP. NET MVC uses Authenticationattribute authentication login

Source: Internet
Author: User

First, add a class Authenticationattribute, which inherits Authorizeattribute, as follows:

usingsystem.web;usingSYSTEM.WEB.MVC;namespacezhong.web{ Public classAuthenticationattribute:authorizeattribute { Public Override voidonauthorization (AuthorizationContext filtercontext) {//base.            Onauthorization (Filtercontext); //if the controller does not have the AllowAnonymous feature or the action does not have the AllowAnonymous feature checked            if(!filtercontext.actiondescriptor.isdefined (typeof(Allowanonymousattribute),true) &&!filtercontext.actiondescriptor.controllerdescriptor.isdefined (typeof(Allowanonymousattribute),true))            {                //write here to determine whether the logical code to log in//Here the cookie is used to determine whether to log in, in order to simply explain how the feature is used, the cookie records the user name and plaintext password (in practice, such as encryption and other processing)HttpCookie cookie = filtercontext.httpcontext.request.cookies["Member"]; if(! (cookie!=NULL&& cookies. values["name"] =="Test"&& cookies. values["Pass"] =="123") ) {Filtercontext.result=NewRedirectresult ("/member/login"); }            }        }    }}
View Code

Add features in Membercontroll Authentication,member controller There are three action methods, one is the home index, one is login page login, one is to process the Post mode login page login, The View code for index corresponds to the following:

@{    viewbag.title = "Index";} < H2 > This is the Member Center </h2>

The View code for login corresponds to the following:

@{viewbag.title = "Login";}<H2>Member Login</H2>@using (Html.BeginForm ()) {<label>User name:</label><inputtype= "text"name= "Name" /><BR/>    <label>Password:</label><inputtype= "Password"name= "Password" /><BR/>    <inputtype= "Submit"value= "Login" /> }

When there is no login direct access to Member/index, it jumps to login. When you enter the correct user name password to log in, you will be redirected to the index page.

The complete Membercontroller code is as follows:

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingsystem.web;usingSYSTEM.WEB.MVC;namespacezhong.web.controllers{[Authentication] Public classMembercontroller:controller {//Get:member         PublicActionResult Index () {returnView (); } [AllowAnonymous] PublicActionResult Login () {returnView (); } [allowanonymous] [HttpPost] PublicActionResult Login (stringNamestringpassword) {            //here for a simple demonstration of login judgment, mainly to verify the role of Authenticationattribute, the actual application may be to query the database,//Password determination requires encryption processing, etc.            if(Name = ="Test"&& Password = ="123") {HttpCookie cookie=NewHttpCookie ("Member"); Cookies. values["name"] ="Test"; Cookies. values["Pass"] ="123";                RESPONSE.COOKIES.ADD (cookie); returnRedirecttoaction ("Index"); }            returnView (); }    }}
View Code

Special NOTE: Because the controller uses the authentication feature, so the request for all the action under the authorization/login authentication, login is the login page, access to this page is generally not logged in the state, so need to allow anonymous access, so added the [ AllowAnonymous]

Another way to write the above authorizationattribute is to inherit the FilterAttribute and implement the interface Iauthorizationfilter, similar to the authorizeattribute of the system,

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingsystem.web;usingSYSTEM.WEB.MVC;namespacezhong.web{ Public classTestattribute:filterattribute, Iauthorizationfilter { Public voidonauthorization (AuthorizationContext filtercontext) {//throw new NotImplementedException (); //TODO: Write code to implement login verification here        }    }}
View Code

ASP. NET MVC uses Authenticationattribute authentication login

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.