在表单模型中,我曾经通过以下方式获取当前登录用户:
Page.CurrentUser
如何在ASP中获得控制器类中的当前用户。净MVC吗?
在表单模型中,我曾经通过以下方式获取当前登录用户:
Page.CurrentUser
如何在ASP中获得控制器类中的当前用户。净MVC吗?
当前回答
为了引用使用ASP中内置的简单身份验证创建的用户ID。如果你使用数据库优先和实体框架5来生成代码优先绑定,并且你的表是结构化的,因此使用userID的外键,这是很有帮助的),你可以使用
WebSecurity.CurrentUserId
一旦你添加了using语句
using System.Web.Security;
其他回答
如果有人还在读这篇文章,我用下面的方式访问cshtml文件。
<li>Hello @User.Identity.Name</li>
我知道这真的很旧,但我刚刚开始使用ASP。NET MVC,所以我想我要坚持我的两分:
请求。IsAuthenticated告诉您用户是否通过了身份验证。 identity为您提供登录用户的标识。
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));
用户名:System.Web.HttpContext.Current.User.Identity.Name
在Asp.net Mvc Identity 2中,你可以通过以下方式获取当前用户名:
var username = System.Web.HttpContext.Current.User.Identity.Name;