In the past few days, I have used MVC to build a project and HttpContext. user. isInRole (), but every time I use it, HttpContext. user. isInRole ("Admin") always returns false. I checked a lot of information on the Internet and found that it was not solved. To solve the problem, we should also implement a series of extension methods. Well, let's talk nonsense. The topic is officially entered:
Permission judgment
If (HttpContext. User. Identity = null | String. IsNullOrEmpty (HttpContext. User. Identity. Name ))
{
Return Redirect ("~ /Account/LogOn? ReturnUrl =/service ");
}
Else if (HttpContext. User. IsInRole ("Admin "))
{
Return RedirectToAction ("Index", "AdminService ");
}
Else
{
.......
}
In the above Code, HttpContext. User. IsInRole ("Admin") returns false. What should we do if we return True?
Add the following method to Global. asax:
View Code
/// <Summary>
/// Authen right for user
/// </Summary>
/// <Param name = "sender"> </param>
/// <Param name = "e"> </param>
Protected void Application_AuthenticateRequest (Object sender, EventArgs e)
{
If (HttpContext. Current. User! = Null)
{
If (HttpContext. Current. User. Identity. IsAuthenticated)
{
If (HttpContext. Current. User. Identity is FormsIdentity)
{
// Get current user identitied by forms
FormsIdentity id = (FormsIdentity) HttpContext. Current. User. Identity;
// Get FormsAuthenticationTicket object
FormsAuthenticationTicket ticket = id. Ticket;
String userData = ticket. UserData;
String [] roles = userData. Split (',');
// Set the new identity for current user.
HttpContext. Current. User = new GenericPrincipal (id, roles );
}
}
}
}
After adding the user, go to your logon page and grant permissions to the current user. See:
LogOn
[HttpPost]
Public ActionResult LogOn (LogOnModel model, string returnUrl)
{
If (ModelState. IsValid)
{
If (ValidateUser (model. UserName, model. Password )))
{
UserInfo userInfo = GetuserInfo (model. UserName );
If (userInfo. Role = "Admin "){
Role = "Admin ";
}
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket (1,
UserInfo. Alias,
DateTime. Now,
DateTime. Now. AddMinutes (30 ),
False,
Role );
String encTicket = FormsAuthentication. Encrypt (authTicket );
This. Response. Cookies. Add (new HttpCookie (FormsAuthentication. FormsCookieName, encTicket ));
// FormsAuthentication. SetAuthCookie (model. UserName, model. RememberMe );
If (Url. IsLocalUrl (returnUrl) & returnUrl. Length> 1 & returnUrl. StartsWith ("/")
&&! ReturnUrl. StartsWith ("//")&&! ReturnUrl. StartsWith ("/\\"))
{
Return Redirect (returnUrl );
}
Else
{
Return RedirectToAction ("Index", "Home ");
}
}
Else
{
ModelState. AddModelError ("", "The user name or password provided is incorrect .");
}
}
// If we got this far, something failed, redisplay form
Return View (model );
}
Well, all the problems have been solved. If you have other good methods, you can share them with us. Please leave a message to correct them :)