在表单模型中,我曾经通过以下方式获取当前登录用户:

Page.CurrentUser

如何在ASP中获得控制器类中的当前用户。净MVC吗?


当前回答

为了引用使用ASP中内置的简单身份验证创建的用户ID。如果你使用数据库优先和实体框架5来生成代码优先绑定,并且你的表是结构化的,因此使用userID的外键,这是很有帮助的),你可以使用

WebSecurity.CurrentUserId

一旦你添加了using语句

using System.Web.Security;

其他回答

这个页面可能就是你要找的: 在MVC3中使用Page.User.Identity.Name

你只需要User.Identity.Name。

不管怎样,在ASP中。NET MVC 3你可以使用User来返回当前请求的用户。

var ticket = FormsAuthentication.Decrypt(
                    HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName].Value);

if (ticket.Expired)
{
    throw new InvalidOperationException("Ticket expired.");
}

IPrincipal user =  (System.Security.Principal.IPrincipal) new RolePrincipal(new FormsIdentity(ticket));

您可以在ASP中获取用户名。NET MVC4:

System.Web.HttpContext.Current.User.Identity.Name

如果需要从控制器内部获取用户,请使用controller的user属性。如果你从视图中需要它,我会在ViewData中填充你特别需要的东西,或者你可以只调用User,因为我认为它是ViewPage的一个属性。