在asp.net mvc中使用context.User.Identity.Name有什么用?

Ran*_*rez 1 c# asp.net visual-studio asp.net-mvc-3

我正在学习asp.net mvc,我刚开始,我决定从网络表格转移到mvc.

我正在从codeplex mvc音乐商店学习这个教程,而且这段代码我不明白它是如何使用的以及为什么使用它.

这是代码行:

if(!string.IsNullOrWhiteSpace(context.User.Identity.Name))
                {
                    context.Session[CartSessionKey] = context.User.Identity.Name;

                }
Run Code Online (Sandbox Code Playgroud)

我想知道什么context.User.Identity.Name,因为我尝试删除它包含的if块,应用程序仍然有效.

这是该函数的完整代码:

 public string GetCartId(HttpContextBase context)
        {
            if (context.Session[CartSessionKey] == null)
            {
                if(!string.IsNullOrWhiteSpace(context.User.Identity.Name))
                {
                    context.Session[CartSessionKey] = context.User.Identity.Name;

                }
                else
                {
                    // Generate a new random GUID using System.Guid class
                    Guid tempCartId = Guid.NewGuid();
                    // Send tempCartId back to client as a cookie
                    context.Session[CartSessionKey] = tempCartId.ToString();
                }
            }
            return context.Session[CartSessionKey].ToString();
        }
Run Code Online (Sandbox Code Playgroud)

Ica*_*rus 5

当您需要身份验证时,它与Web窗体中的操作完全相同.用户成功通过身份验证后,将context.User.Identity.Name包含登录人员的用户名.

在您的特定示例中,它只是检查用户是否已经过身份验证 - 尽管您应该检查Request.IsAuthenticated而不是检查Username是否为空或空白 - 并将该用户的用户名放入Session[CartSessionKey]