Accessing User.Identity from Master Page
I'm trying to access User.Identity from my master page so I can figure out which user is logged in, however I can't get it to work. If I import System.Security.Principal
in my master page it makes no difference:
<%@ Import Namespace="System.Security.Principal" %>
I can access it fine if I try within a Controller.
Any idea what I need to do?
What about through HttpContext.Current.User.Identity
?
<%=HttpContext.Current.User.Identity.Name %>
Will display the current users name
HttpContext.Current.User
will get the IPrincipal object.
Here is a master page that only displays the Username in the title:
<%@ 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>
I think Its Work
HttpContext.Current.User.Identity.Name.ToString()
or
Page.User.Identity.Name.ToString()
You can use HttpContext.Current.User.Name
but you need to remember that the Master Page
code is executed only after the slave page code. So you can use this variable as long as you are not performing any security logic in the master page.
You can get this from:
Context.User.Identity.Name
精彩评论