我是asp.net mvc 2的新手。我正在通过做一个测试项目来学习mvc。 我正在使用formsauthentication登录我的网站。在登录期间,我能够登录网站,但我没有获得用户身份。
我已将http://www.dotnetfunda.com/articles/article141.aspx作为我的参考网站
在我的webconfig文件中。
<authentication mode="Forms">
<forms loginUrl="~/Home/login" defaultUrl="~/Home/login" cookieless="UseCookies" slidingExpiration="true" timeout="20" />
</authentication>
登录控制器中的
public ActionResult Login(LogOnModel logon)
{
if (ModelState.IsValid)
{
if (FormsService.SignIn(logon.UserName, logon.Password) == true)
{
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, // version
FormsService.Username, // user name
DateTime.Now, // create time
DateTime.Now.AddSeconds(30), // expire time
false, // persistent
FormsService.Role,
FormsAuthentication.FormsCookiePath); // user data, such as roles
string hashCookies = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashCookies);
Response.Cookies.Add(cookie);
if (FormsService.Role == "Brand")
{
return RedirectToAction("Index", "Creative");
}
else if (FormsService.Role == "Creative")
{
return RedirectToAction("Index", "Creative");
}
}
}
return View();
}
在userlogoncontrol中的我做了这样的更改。 但它没有显示用户名和我的垃圾箱。
<%
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
%>
Welcome <b><%= Html.Encode(Page.User.Identity.Name) %></b>!
[ <%= Html.ActionLink("Log Off", "LogOff", "Account") %> ] |
<%
if(HttpContext.Current.User.IsInRole("Brand"))
{
%>
[ <%= Html.ActionLink("my bin", "Bin", "Brand") %> ] |
<%
}
else if (HttpContext.Current.User.IsInRole("Creative"))
{
%>
[ <%= Html.ActionLink("my bin", "Bin", "Creative") %> ] |
<%
}
}
else
{
%>
[ <%= Html.ActionLink("Log On", "LogOn", "Account") %> ]
<%
}
%>
我是否遗漏了任何内容?如何在cookie中保存用户ID和角色等用户详细信息。
答案 0 :(得分:2)
您链接的文章是关于WebForms的。在ASP.NET MVC中,我建议您使用自定义[Authorize]
过滤器。你的Login
看起来不错。你可以保持这样。然后编写自定义Authorize属性:
public class MyAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var isAuthorized = base.AuthorizeCore(httpContext);
if (isAuthorized)
{
var cookie = httpContext.Request.Cookies[FormsAuthentication.FormsCookieName];
if (cookie != null)
{
var ticket = FormsAuthentication.Decrypt(cookie.Value);
var roles = ticket.UserData.Split(',');
var identity = new GenericIdentity(ticket.Name);
httpContext.User = new GenericPrincipal(identity, roles);
}
}
return isAuthorized;
}
}
现在使用此自定义属性修饰控制器/操作:
[MyAuthorize]
public ActionResult Foo()
{
// here the this.User property will represent the custom principal
...
}
现在需要触摸Global.asax
。
答案 1 :(得分:1)
_identity = Thread.CurrentPrincipal.Identity;