如何在 ASP.NET MVC 中为 HttpContext.User 赋值?
我编写了如下控制器:
public class AccountController : Controller
{
public ActionResult Login(/*---*/)
{
GenericIdentity identity = new GenericIdentity("userName");
GenericPrincipal principal = new GenericPrincipal(identity, new string[] { "role1", "role2" });
this.HttpContext.User = principal;
/*---*/;
}
}
登录后,我可以在其他控制器中通过 User.Identity.Name 获取用户名。 但 User.IsInRole("role1") 总是返回 false。
我如何为用户分配一个值,我不想使用会员资格......
I write a controller like below:
public class AccountController : Controller
{
public ActionResult Login(/*---*/)
{
GenericIdentity identity = new GenericIdentity("userName");
GenericPrincipal principal = new GenericPrincipal(identity, new string[] { "role1", "role2" });
this.HttpContext.User = principal;
/*---*/;
}
}
After login, I can get user name by User.Identity.Name in other controller.
But User.IsInRole("role1") always return false.
How can I assign a value to User, I don't want to use Membership...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要将用户数据保存在某处,以便所有后续页面请求都可以访问它。通常您会创建一个身份验证票证并将其存储在 cookie 中。然后,对于每个请求,您提取数据并创建您的 IPrincipal。这可以在 Global.ascx 的
Application_AuthenticateRequest
方法中完成,MVC - 如何存储/分配经过身份验证的用户的角色提供了有关执行您想要的操作的简单方法的更多信息。
You need to persist the user data somewhere so that all subsequent page requests have access to it. Usually you would create an authentication ticket and store it in a cookie. Then for each request you extract the data and create your IPrincipal. This can be done in the
Application_AuthenticateRequest
method of Global.ascx,MVC - How to store/assign roles of authenticated users has more information on a simple way to do what you want.
嗯。
使用会员资格?
至少是较低级别的API。在某些情况下,您需要为其分配一个主体(它基本上会变成一个 cookie,并在每次调用时反序列化)。
详细信息位于 http://support.microsoft.com/kb/306590
或也位于 < a href="http://msdn.microsoft.com/en-us/library/aa302399.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/aa302399.aspx
Hm.
Using membership?
At least the lower level API. You need to assign it a principal in some event (which basically turns into a cookie and is deserialized with every call).
Details are in http://support.microsoft.com/kb/306590
Or also in http://msdn.microsoft.com/en-us/library/aa302399.aspx