1, User login
Verify that the user is logged in successfully steps to ignore, the user login successfully after how to save the current user login information (session,cookie), this article describes the authentication (in fact, is based on cookies), the following look at the code.
Introduction of namespaces
Using System.Web.Security;
Copy Code code as follows:
Users modeluser = new users () {ID = 10000, Name = UserName, UserName = UserName, PassWord = PassWord, Roles = "admin"};/ /user Entities
String UserData = Serializehelper.instance.jsonserialize<users> (Modeluser);//serialization of user entities
Save the identity information, the parameter description can see the hint
FormsAuthenticationTicket Ticket = new FormsAuthenticationTicket (1, UserName, DateTime.Now, DateTime.Now.AddHours (12) , false, UserData);
HttpCookie Cookie = new HttpCookie (Formsauthentication.formscookiename, Formsauthentication.encrypt (Ticket)); Encrypt identity information, save to Cookie
RESPONSE.COOKIES.ADD (Cookie);
Now that the identity is stored in a cookie, what happens when a scene needs to use the user ID or other information of the current user?
So, we get the identity information in the cookie, then decrypt it, and then deserialize it into the user entity, OK.
Copy Code code as follows:
<summary>
Get User Login Information
</summary>
<returns></returns>
Public Users GetUser ()
{
if (HttpContext.Current.Request.IsAuthenticated)//Is authenticated
{
HttpCookie Authcookie = httpcontext.current.request.cookies[formsauthentication.formscookiename];//Get cookies
FormsAuthenticationTicket Ticket = Formsauthentication.decrypt (authcookie.value);//decryption
Return serializehelper.instance.jsondeserialize<users> (Ticket.userdata);//deserialization
}
return null;
}
2. Permission Verification
Here is the action interceptor in MVC (overriding onactionexecuting), which runs the code in the interceptor before the action executes. At the same time, it is possible to authenticate for expiration.
Copy Code code as follows:
<summary>
Permission validation
</summary>
public class Authattribute:actionfilterattribute
{
<summary>
Role name
</summary>
public string Code {get; set;}
<summary>
Verify permissions (this is done first before action executes)
</summary>
<param name= "Filtercontext" ></param>
public override void OnActionExecuting (ActionExecutingContext filtercontext)
{
If there is identity information
if (! HttpContext.Current.User.Identity.IsAuthenticated)
{
Contentresult Content = new Contentresult ();
Content.content = string. Format ("<script type= ' Text/javascript ') >alert (' Please log in first!") '); window.location.href= ' {0} ';</script> ', formsauthentication.loginurl);
Filtercontext.result = Content;
}
Else
{
string[] Role = CheckLogin.Instance.GetUser (). Roles.split (', ');/Get all roles
if (! Role.contains (Code))//Authentication Permissions
{
Validation does not pass
Contentresult Content = new Contentresult ();
Content.content = "<script type= ' text/javascript ' >alert (' permission validation does not pass!") '); History.go ( -1);</script> ";
Filtercontext.result = Content;
}
}
}
}
So how do you call it in action? Here, put the code in the HomeController to see.
Copy Code code as follows:
public class Homecontroller:basecontroller
{
[Authattribute (Code = "admin")]//authenticated (this action only allows admin to view)
Public ActionResult Index ()
{
Users Modeluser = CheckLogin.Instance.GetUser ();
Return View (Modeluser);
}
[Authattribute (Code = "user")]//validation does not pass
Public ActionResult Index2 ()
{
return View ();
}
[Authattribute (Code = "admin")]//validation passed, an exception occurred
Public ActionResult Index3 ()
{
return View ();
}
}
This allows you to control the permissions to the action.
3. Exception handling
The above HomeController not to inherit controller, but to inherit our own definition of a basecontroller, then let's see what is written in Basecontroller?
Copy Code code as follows:
[Errorattribute]
public class Basecontroller:controller
{
All controller inherit Basecontroller, then an exception capture occurs
}
Here Basecontroller only do one thing, is to add a errorattribute error interceptor, so as long as the exception occurred in controller will be processed in Errorattribute, you can log to the database and other operations. So let's see how Errorattribute works.
Copy Code code as follows:
<summary>
Error log (This is done here when an exception occurs controller)
</summary>
public class Errorattribute:actionfilterattribute, Iexceptionfilter
{
<summary>
Abnormal
</summary>
<param name= "Filtercontext" ></param>
public void Onexception (Exceptioncontext filtercontext)
{
Get exception information, save in storage
Exception Error = filtercontext.exception;
String message = error.message;//error messages
String Url = httpcontext.current.request.rawurl;//Error occurrence address
Filtercontext.exceptionhandled = true;
Filtercontext.result = new Redirectresult ("/error/show/");//Jump to error Prompt page
}
}
Here you can catch the exception and jump to the friendly error prompt page. Several operations in MVC can be done so easily, and the code will provide downloads below the article.
Instance Code
Author: lying.net