1. User Logon
This document describes how to save the current user's logon information (session, cookie) after a user successfully logs on. This document describes identity authentication (in fact, it is based on cookies, next let's look at the code.
Introduce namespace
Using System. Web. Security;
Copy codeThe Code is as follows:
Users ModelUser = new Users () {ID = 10000, Name = UserName, UserName = UserName, PassWord = PassWord, Roles = "admin"}; // user entity
String UserData = SerializeHelper. Instance. JsonSerialize <Users> (ModelUser); // serialize user entities
// Save the identity information. For more information about the parameters, see the prompt.
FormsAuthenticationTicket Ticket = new FormsAuthenticationTicket (1, UserName, DateTime. Now, DateTime. Now. AddHours (12), false, UserData );
HttpCookie Cookie = new HttpCookie (FormsAuthentication. FormsCookieName, FormsAuthentication. Encrypt (Ticket); // Encrypt the identity information and save it to Cookie
Response. Cookies. Add (Cookie );
Now the identity information is saved to the cookie. What should I do if I need to use the user ID or other information of the current user?
Then, we get the identity information again in the cookie, decrypt it, And deserialize it into a user entity.
Copy codeThe Code is as follows:
/// <Summary>
/// Obtain user logon information
/// </Summary>
/// <Returns> </returns>
Public Users GetUser ()
{
If (HttpContext. Current. Request. IsAuthenticated) // whether the authentication is successful
{
HttpCookie authCookie = HttpContext. Current. Request. Cookies [FormsAuthentication. FormsCookieName]; // get cookie
FormsAuthenticationTicket Ticket = FormsAuthentication. Decrypt (authCookie. Value); // Decrypt
Return SerializeHelper. Instance. JsonDeserialize <Users> (Ticket. UserData); // deserialization
}
Return null;
}
2. Permission Verification
Here, the action interceptor in MVC (rewrite OnActionExecuting) is used. Before the action is executed, the code in the interceptor is run. Here, you can also verify whether the authentication has expired.
Copy codeThe Code is as follows:
/// <Summary>
/// Permission Verification
/// </Summary>
Public class AuthAttribute: ActionFilterAttribute
{
/// <Summary>
/// Role name
/// </Summary>
Public string Code {get; set ;}
/// <Summary>
/// Verify the permission (this will be executed before the action is executed)
/// </Summary>
/// <Param name = "filterContext"> </param>
Public override void OnActionExecuting (ActionExecutingContext filterContext)
{
// If identity information exists
If (! HttpContext. Current. User. Identity. IsAuthenticated)
{
ContentResult Content = new ContentResult ();
Content. Content = string. Format ("<script type = 'text/javascript '> alert ('Log On first! '); Window. location. href =' {0} '; </script> ", FormsAuthentication. LoginUrl );
FilterContext. Result = Content;
}
Else
{
String [] Role = CheckLogin. Instance. GetUser (). Roles. Split (','); // obtain all Roles
If (! Role. Contains (Code) // verify the permission
{
// Verification fails
ContentResult Content = new ContentResult ();
Content. Content = "<script type = 'text/javascript '> alert ('permission Verification Failed! '); History. go (-1); </script> ";
FilterContext. Result = Content;
}
}
}
}
So how to call it in action? Paste the code in HomeController here.
Copy codeThe Code is as follows:
Public class HomeController: BaseController
{
[AuthAttribute (Code = "admin")] // authentication passed (this action can only be viewed by the admin)
Public ActionResult Index ()
{
Users ModelUser = CheckLogin. Instance. GetUser ();
Return View (ModelUser );
}
[AuthAttribute (Code = "user")] // verification fails
Public ActionResult Index2 ()
{
Return View ();
}
[AuthAttribute (Code = "admin")] // verification passed, exception
Public ActionResult Index3 ()
{
Return View ();
}
}
In this way, you can control the permission to action.
3. Exception Handling
The above HomeController does not inherit the Controller, but a BaseController defined by ourselves. So let's take a look at what is written in BaseController?
Copy codeThe Code is as follows:
[ErrorAttribute]
Public class BaseController: Controller
{
// If all controllers inherit the BaseController, exception capture is performed.
}
Here, BaseController only does one thing, that is, it adds an ErrorAttribute error Interceptor. If exceptions occur in the Controller, they will be processed in ErrorAttribute, you can record operations to the database. Let's see how ErrorAttribute works.
Copy codeThe Code is as follows:
/// <Summary>
/// Error Log (this will be executed when the Controller encounters an exception)
/// </Summary>
Public class ErrorAttribute: ActionFilterAttribute, IExceptionFilter
{
/// <Summary>
/// Exception
/// </Summary>
/// <Param name = "filterContext"> </param>
Public void OnException (ExceptionContext filterContext)
{
// Obtain the exception information and store it in the database
Exception Error = filterContext. Exception;
String Message = Error. Message; // Error Message
String Url = HttpContext. Current. Request. RawUrl; // address where an error occurs
FilterContext. ExceptionHandled = true;
FilterContext. Result = new RedirectResult ("/Error/Show/"); // jump to the Error prompt page
}
}
Here you can capture exceptions and jump to the friendly error prompt page. Several operations in MVC can be simply done in this way, and the code will be downloaded below the article.
Instance code
Author: LyIng. Net