控制器中的windows标识代码重复

本文关键字:代码 标识 windows 控制器 | 更新日期: 2023-09-27 18:19:54

_Layout.cshtml

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

MyController.cs

公共类MyController:Controller{public ActionResult Index(){System.Security.Principal.WindowsIdentity wi=System.Security.PPrincipal.WindowsIdentity.GetCurrent();string[]a=User.Identity.Name.Split('''''''');System.DirectoryServices.DirectoryEntry ADEntry=新System.DirectoryService.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.PPrincipal.WindowsIdentity.GetCurrent();string[]a=User.Identity.Name.Split('''''''');System.DirectoryServices.DirectoryEntry ADEntry=新System.DirectoryService.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.PPrincipal.WindowsIdentity.GetCurrent();string[]a=User.Identity.Name.Split('''''''');System.DirectoryServices.DirectoryEntry ADEntry=新System.DirectoryService.DirectoryEntry("WinNT://"+a[0]+"/"+a[1]);ViewBag.Username=ADEntry.Properties["FullName"].Value.ToString();return View();}}

我怎么能把这个逻辑放在一个地方,这样我就不会重复自己了?我需要在所有布局中显示用户名。

控制器中的windows标识代码重复

覆盖控制器中的OnActionExecuting方法,并将设置Username的代码放在那里。

  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类中。

您可以使用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
{
}

您可以尝试将一些逻辑移动到您的模型中。让你的控制器瘦下来,模特胖起来。