我正在尝试查看View中的用户角色:
@if (User.IsInRole("User"))
但是总是假,
User.Identity.IsAuthenticated
User.Identity.Name
返回true和名称。
我的表单身份验证服务:
public static void SignIn(string userName, string role, bool createPersistentCookie)
{
FormsAuthenticationTicket authTicket = new
FormsAuthenticationTicket(1,
userName,
DateTime.Now,
DateTime.Now.AddMinutes(30),
createPersistentCookie,
role);
string encTicket = FormsAuthentication.Encrypt(authTicket);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket)
{
Expires = authTicket.Expiration,
Path = FormsAuthentication.FormsCookiePath
};
if (HttpContext.Current != null)
{
HttpContext.Current.Response.Cookies.Add(cookie);
}
}
并致电
FormsAuthenticationService.SignIn(model.UserName, "User", true);
答案 0 :(得分:0)
通过添加到Global.asax来解决:
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie == null || authCookie.Value == "")
return;
FormsAuthenticationTicket authTicket;
try
{
authTicket = FormsAuthentication.Decrypt(authCookie.Value);
}
catch
{
return;
}
string[] roles = authTicket.UserData.Split(';');
if (Context.User != null)
Context.User = new GenericPrincipal(Context.User.Identity, roles);
}