控制器中重复的Windows身份代码

时间:2012-01-09 20:24:36

标签: c# asp.net asp.net-mvc-3

_Layout.cshtml

<span>Hello @ViewBag.Username!</span>

MyController.cs

    public class MyController : Controller
    {
        public ActionResult Index()
        {
        System.Security.Principal.WindowsIdentity wi = System.Security.Principal.WindowsIdentity.GetCurrent();
        string[] a = User.Identity.Name.Split('\\');
        System.DirectoryServices.DirectoryEntry ADEntry = new System.DirectoryServices.DirectoryEntry("WinNT://" + a[0] + "/" + a[1]);
        ViewBag.Username = ADEntry.Properties["FullName"].Value.ToString();

        return View();
    }

    public ActionResult NextView()
    {
        System.Security.Principal.WindowsIdentity wi = System.Security.Principal.WindowsIdentity.GetCurrent();
        string[] a = User.Identity.Name.Split('\\');
        System.DirectoryServices.DirectoryEntry ADEntry = new System.DirectoryServices.DirectoryEntry("WinNT://" + a[0] + "/" + a[1]);
        ViewBag.Username = ADEntry.Properties["FullName"].Value.ToString();

        return View();
    }

    public ActionResult AnotherView()
    {
        System.Security.Principal.WindowsIdentity wi = System.Security.Principal.WindowsIdentity.GetCurrent();
        string[] a = User.Identity.Name.Split('\\');
        System.DirectoryServices.DirectoryEntry ADEntry = new System.DirectoryServices.DirectoryEntry("WinNT://" + a[0] + "/" + a[1]);
        ViewBag.Username = ADEntry.Properties["FullName"].Value.ToString();

        return View();
    }
}

我如何将这个逻辑放在一个地方,这样我才不会重复自己?我需要在我的所有布局中显示用户名。

3 个答案:

答案 0 :(得分:2)

覆盖控制器中的OnActionExecuting方法并输入代码以在那里设置用户名。

  protected override void OnActionExecuting(ActionExecutingContext filterContext)
  {
     System.Security.Principal.WindowsIdentity wi = System.Security.Principal.WindowsIdentity.GetCurrent();
     string[] a = User.Identity.Name.Split('\\');
     System.DirectoryServices.DirectoryEntry ADEntry = new System.DirectoryServices.DirectoryEntry("WinNT://" + a[0] + "/" + a[1]);
     ViewBag.Username = ADEntry.Properties["FullName"].Value.ToString();

     base.OnActionExecuting(filterContext);
  }

然后您不需要设置ViewBag.Username属性。控制器中的任何方法都已经设置好了。如果需要跨多个控制器,请将其放入基本的Controller类中。

答案 1 :(得分:1)

您可以使用BaseController并将其继承到您创建的所有控件,如下所示。

 public class BaseController : Controller
 {
       protected override void OnActionExecuting(ActionExecutingContext filterContext)
       {
            System.Security.Principal.WindowsIdentity wi =    System.Security.Principal.WindowsIdentity.GetCurrent();
      string[] a = User.Identity.Name.Split('\\');
      System.DirectoryServices.DirectoryEntry ADEntry = new   System.DirectoryServices.DirectoryEntry("WinNT://" + a[0] + "/" + a[1]);
     ViewBag.Username = ADEntry.Properties["FullName"].Value.ToString();

     base.OnActionExecuting(filterContext);
  }
}

public class MyController : BaseController
{

}

答案 2 :(得分:0)

您可以尝试将一些逻辑移入模型中。让你的控制器瘦,模型脂肪。