访问HTMLHelper类中的User.Identity.Name

Jon*_*Jon 10 asp.net-mvc

我正在写一个HTMLHelper,但我需要访问User.Identity.Name,我该怎么做?

eu-*_*-ne 18

public static string YourHtmlHelper(this HtmlHelper html)
{
    var name = html.ViewContext.HttpContext.User.Identity.Name;
}
Run Code Online (Sandbox Code Playgroud)


Mik*_*ise 5

您可能想要在尝试获取名称之前检查并查看User.Identity是否为空.

    public static string YourHtmlHelper(this HtmlHelper html) 
    { 
        var identity = html.ViewContext.HttpContext.User.Identity;

        if (identity != null)
        {
            return html.ViewContext.HttpContext.User.Identity.Name;
        }

        return string.Empty;
    }
Run Code Online (Sandbox Code Playgroud)