Solve the problem that HttpContext. User. IsInRole () always returns false

Source: Internet
Author: User

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 :)

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.