解决HttpContext.User.IsInRole() 永远返回false的问题
这几天在用MVC做一个项目,用到了HttpContext.User.IsInRole() 这个方法,但是每次当我用的时候,HttpContext.User.IsInRole(“Admin”) 返回的永远是false。 在网上查了很多资料,发现都没有解决,要解决的话,也要实现一系列的扩展方法。好,废话少说,正式进入主题:

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
{
…….
}
{
return Redirect("~/Account/LogOn?returnUrl=/service");
}
else if (HttpContext.User.IsInRole("Admin"))
{
return RedirectToAction("Index", "AdminService");
}
else
{
…….
}
上面的代码中HttpContext.User.IsInRole(“Admin”) 返回的是false。我们要返回True怎么办?
在Global.asax中添加以下方法:

/// <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);
}
}
}
}
/// 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);
}
}
}
}
添加好以后,进入你的登录页面,给当前用户授权。请看:

[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);
}
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);
}
好了,直到这里,所有的问题,已经解决了。如果大家有其他的好的方法,可以分享, 欢迎留言指正 :)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· 展开说说关于C#中ORM框架的用法!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?