Update To MVC's LogOnUserControl.ascx

Microsoft has this code for the LogOnUserControl.ascx partial control when you create a brand new ASP.NET MVC application:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<%
    if (Request.IsAuthenticated) {
%>
        Welcome <b><%= Html.Encode(Page.User.Identity.Name) %></b>!
        [ <%= Html.ActionLink("Log Off", "LogOff", "Account") %> ]
<%
    }
    else {
%> 
        [ <%= Html.ActionLink("Log On", "LogOn", "Account") %> ]
<%
    }
%>
However, this isn't 100% correct. It just so happens that Page.User.Identity.Name in their example is the User's name, however really Page.User.Identity.Name in most cases is a unique (primary) key to a users table. This is a little cleaner:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<%
    if (Request.IsAuthenticated) {
%>
        Welcome <b><%= Html.Encode(Membership.GetUser(Page.User.Identity.Name).UserName) %></b>!
        [ <%= Html.ActionLink("Log Off", "LogOff", "Account") %> ]
<%
    }
    else {
%> 
        [ <%= Html.ActionLink("Log On", "LogOn", "Account") %> ]
<%
    }
%>
This change makes sure that we are getting the username (Display Name) from the membership provider regardless of what is used for the key to the provider. {6230289B-5BEE-409e-932A-2F01FA407A92}

Comments

Popular posts from this blog

Yet once more into the breech (of altered programming logic)

Simple WP7 Mango App for Background Tasks, Toast, and Tiles: Code Explanation

How to convert SVG data to a Png Image file Using InkScape