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

Page.CurrentUser

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


当前回答

如果你在登录页面中,以LoginUser_LoggedIn事件为例,Current.User.Identity.Name将返回一个空值,所以你必须使用yourLoginControlName。用户名属性。

MembershipUser u = Membership.GetUser(LoginUser.UserName);

其他回答

在IIS管理器的“身份验证”下,禁用: 1)匿名认证 2)表单认证

然后添加以下到你的控制器,以处理测试和服务器部署:

string sUserName = null;
string url = Request.Url.ToString();

if (url.Contains("localhost"))
  sUserName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
else
  sUserName = User.Identity.Name;

在Asp.net Mvc Identity 2中,你可以通过以下方式获取当前用户名:

var username = System.Web.HttpContext.Current.User.Identity.Name;

用户名:

User.Identity.Name

但如果你只需要获取ID,你可以使用:

using Microsoft.AspNet.Identity;

所以,你可以直接获得用户ID:

User.Identity.GetUserId();

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

我知道这真的很旧,但我刚刚开始使用ASP。NET MVC,所以我想我要坚持我的两分:

请求。IsAuthenticated告诉您用户是否通过了身份验证。 identity为您提供登录用户的标识。