Повторный идентификационный код Windows в контроллере - PullRequest
0 голосов
/ 10 января 2012

_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 ]

2 голосов
/ 10 января 2012

Переопределите метод 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 голос
/ 10 января 2012

Вы можете использовать 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
{

}
0 голосов
/ 10 января 2012

Вы можете попробовать перенести некоторую логику в вашу модель. Делаем ваш контроллер тощим и жирным.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...