-3

As per my question. Will this generates the same username for anonymous and logged in user?

EDIT: sorry for the confusing question. What I'm trying to find out is that if User.Identity.Name is a reliable way to get the username of currently logged in user. Trying to avoid Membership.GetUser().Username as GetUser() might return null for anonymous user.

4

1 回答 1

5

我不确定生成是最好的词。我将假设您的意思是Return the same data

答案并不总是

User.Identity是一个IIdentity实例(通常是GenericIdentityWindowsIdentity)。

Membership.Getuser()将返回MembershipUser的一个实例。

这两种机制都可以定制,并且在技术上可以返回完全不同的信息。

为编辑更新

首先,这个问题开始听起来像一个XY 问题。我强烈建议您让我们知道您实际要解决的问题

虽然Membership.GetUser()应该为匿名用户返回 null,但User.Identity.Name通常string.Empty为匿名用户返回,这在技术上也不正确。

通常推荐的方法是执行以下操作:(直接取自 ASP.Net MVC 3 Template starter)

@if(Request.IsAuthenticated) 
{
  <text>Welcome <b>@Context.User.Identity.Name</b>!
  [ @Html.ActionLink("Log Off", "LogOff", "Account") ]</text>
}
else 
{
  @:[ @Html.ActionLink("Log On", "LogOn", "Account") ]
}
于 2013-05-06T05:09:45.620 回答