Asp. NET cookie and Fiter implementation simple login, allowanonymous anonymous Login

Source: Internet
Author: User
Tags httpcontext send cookies

Send cookies to the server

At the time of landing, we can send a cookie to the server via the following code, including our own account information (not involving encryption), to be used to judge the visitor later.

1HttpCookie cookie =NewHttpCookie ("UserInfo");//Create a new cookie named UserInfo2Cookies. values["UserName"] = Username;//adding account information to a cookie3Cookies. values["PassWord"] = UserPassword;//Adding password information to a cookie4Cookies. Expires = DateTime.MaxValue;//set the amount of time that a cookie can exist, the maximum time that is set here, and a cookie. Expires = System.DateTime.Now.AddDays (1);//set the presence time 1 days5RESPONSE.COOKIES.ADD (cookie);//Write Cookie

Filter filters

It is not only when we log in that we need to request a response cookie, but when we visit any page, we need to verify the cookie information and judge the visitor who is currently accessing the page, so in theory, every controller, every action, we need to write code about the cookie. , it is clear that such a huge workload is impossible. The problem is solved by the filter filter.

First we customize a filter

1        Public classChecklogin:actionfilterattribute2       {3            Public Override voidonactionexecuted (actionexecutedcontext filtercontext)4          {5HttpCookie cookie = HttpContext.Current.Request.Cookies.Get ("UserInfo");//gets the cookie named UserInfo in all cookies currently requested6  7             if(cookie==NULL|| Cookies. values["UserName"] ==NULL|| Cookies. values["PassWord"] ==NULL)//Determine account password information8             {9Filtercontext.result =NewRedirectresult ("/account/login");//If the account password is null or the cookie does not exist, return to the login pageTen              } One         } A      } -}

This filter is placed on the controller or action can be implemented to verify the role of cookies, but the number of Controller and action needs to function too much, we need to apply the filter to the global, all the controller role.

1 public     class    {3 public         static void        {5         6             filters. ADD (New Handleerrorattribute ()); 7             filters. ADD (New   }10}
1 public     class    {3         protected void                     }8}   

Anonymous access

Follow the above code to log in, you will find that there is no login page, the reason is that the above global role of the filter, even the login page has not been spared, that is, you even enter the landing page will also need to verify information, no information you will return to the login page, but landing page you can not access. Finally, the error.

So for some specific pages, we need to be able to access anonymously, which is also a very practical problem, many pages we do not need to login can be very easy to access.

For anonymous access we need to use: [AllowAnonymous], to be able to skip authentication, to achieve anonymous access.

1     Public classChecklogin:actionfilterattribute2     {3          Public Override voidonactionexecuted (actionexecutedcontext filtercontext)4         {5             varActionfilters = FilterContext.ActionDescriptor.GetCustomAttributes (false);//get all the descriptors6 7             foreach(varIteminchactionfilters)8             {9                 if(item. GetType (). Name = ="Allowanonymousattribute")//If the descriptor type has Allowanonymousattribute (the name of the allowanonymous type), it is accessed directly and does not require validationTen                 { One                     return; A                 } -             }           -HttpCookie cookie = HttpContext.Current.Request.Cookies.Get ("UserInfo");//gets the cookie named UserInfo in all cookies currently requested the  -             if(cookie==NULL|| Cookies. values["UserName"] ==NULL|| Cookies. values["PassWord"] ==NULL)//Determine account password information -             { -Filtercontext.result =NewRedirectresult ("/account/login");//If the account password is null or the cookie does not exist, return to the login page +             } -         } +}

In this way, we can achieve anonymous login, without the need to verify the cookie, you can log on some pages.

Finally, for information that needs to be verified by the current visitor, it is easy to find it in the database based on the account information in the cookie that is taken, which is not explained here. In addition, the cancellation of an account can also be done via an expired cookie.

PS: Only contact computer program, is also the first time to write a blog. feel that blogging is very necessary, this is a thinking learning process, solve the problem is not the end, can write it down, explain to others to solve the problem, is a perfect end! But unfortunately, this time I didn't do it! Limited skill, The positive is highly affected by everybody's criticism!

Reference content:

http://blog.csdn.net/jin3226390/article/details/3245519 (The operation of the cookie is detailed)

Http://www.cnblogs.com/kissdodog/archive/2013/01/21/2869298.html (MVC custom filter)

  

Asp. NET cookie and Fiter implementation simple login, allowanonymous anonymous 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.