在MVC中如何在没有Windows身份验证的情况下获取用户名

时间:2017-12-07 16:50:36

标签: c# asp.net-mvc

在MVC中,我发现代码在不使用Windows身份验证的情况下获取Windows用户名,但无法引用它。

using MvcWinUser.Extensions;

ViewBag.GetWindowsUserName = WindowsIdentityHelper.GetLoginUserName();

错误:非静态字段,方法或属性'MvcWinUser.Extensions.WindowsIdentityHelper.GetLoginUserName()'

需要对象引用

拥有以下内容:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using System.Threading;
using System.Security.Permissions;
using System.Security.Principal;

namespace MvcWinUser.Extensions
{
    public class WindowsIdentityHelper
    {
        public WindowsPrincipal GetWindowsPrincipal()
        {
            //Get Current AppDomain
            AppDomain myDomain = Thread.GetDomain();
            myDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
            return (WindowsPrincipal)Thread.CurrentPrincipal;
        }

        public bool IsUserBelongsToWindowsAdministratorGroup()
        {
            WindowsPrincipal myPrincipal = GetWindowsPrincipal();

        if (myPrincipal.IsInRole("Administrators"))
            return true;

            if (myPrincipal.IsInRole(WindowsBuiltInRole.Administrator))
                return true;
            else
                return false;
        }

        public string GetFullDomainLoginUserName()
        {
            WindowsPrincipal myPrincipal = GetWindowsPrincipal();
            return myPrincipal.Identity.Name.ToString();
        }

        public string GetLoginUserName()
        {
            string authenticatedUser = string.Empty;
            string userName = GetFullDomainLoginUserName();
            if (userName.Contains("\\"))
                authenticatedUser = userName.Split('\\')[1];
            else
                authenticatedUser = userName;
            return authenticatedUser;
        }
    }
}

0 个答案:

没有答案
相关问题