C# 从母版页访问用户身份
我正在尝试从我的母版页访问User.Identity,以便确定哪个用户已登录,但我无法使其工作。如果我在母版页中导入C# 从母版页访问用户身份,c#,asp.net,asp.net-mvc-2,C#,Asp.net,Asp.net Mvc 2,我正在尝试从我的母版页访问User.Identity,以便确定哪个用户已登录,但我无法使其工作。如果我在母版页中导入System.Security.Principal,则没有区别: <%@ Import Namespace="System.Security.Principal" %> 如果我在控制器内尝试,我可以很好地访问它 知道我需要做什么吗?通过HttpContext.Current.User.Identity怎么样?将显示当前用户名 HttpContext.Current
System.Security.Principal
,则没有区别:
<%@ Import Namespace="System.Security.Principal" %>
如果我在控制器内尝试,我可以很好地访问它
知道我需要做什么吗?通过
HttpContext.Current.User.Identity
怎么样?将显示当前用户名
HttpContext.Current.User
将获得IPrincipal对象
以下是仅在标题中显示用户名的母版页:
<%@ Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>
<asp:ContentPlaceHolder ID="TitleContent" runat="server" />
</title>
<link href="../../Content/Style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="page">
<div id="header">
<div id="title">
<h1 id="maintitle">
<%=HttpContext.Current.User.Identity.Name %>
</h1>
</div>
</div>
<div id="main">
<asp:ContentPlaceHolder ID="MainContent" runat="server" />
</div>
</div>
</body>
</html>
您可以从以下位置获得此信息:
Context.User.Identity.Name
您可以使用HttpContext.Current.User.Name
,但您需要记住母版页
代码仅在从版页代码之后执行。因此,只要不在母版页中执行任何安全逻辑,就可以使用此变量。我认为它可以工作
HttpContext.Current.User.Identity.Name.ToString()
或
与公认的答案相比,这增加了什么?Page.User
似乎比HttpContext.Current.User
更干净。只是口味的问题,因为他们做同样的事。我不明白你在说什么
Page.User.Identity.Name.ToString()