【问题标题】:Active Directory fields in ASP.NET MVC4 - unhandled exceptionASP.NET MVC4 中的 Active Directory 字段 - 未处理的异常
【发布时间】:2014-10-02 07:30:36
【问题描述】:

我需要实现一个从 AD 中检索一些字段的类。我已按照此处的说明进行操作:link。但是我从行中得到了一个未处理的异常:

return (UserPrincipalExtended)FindByIdentityWithType(context, typeof(UserPrincipalExtended), identityValue)

我的控制器代码如下所示:

using System.Threading.Tasks;
using System.Net;
using System.Data.Entity;
using System.DirectoryServices.AccountManagement;
(...)

public class HomeController : Controller
{
   private FormsEntities db = new FormsEntities();

   public async Task<ActionResult> Index()
   {          
        UserPrincipalExtended user = UserPrincipalExtended.FindByIdentity(
        new PrincipalContext(ContextType.Domain), User.Identity.Name);          

        var title = user.Title;        
        ViewBag.Message = title;

        return View();
   }

我应该添加任何其他配置吗?以web.config 为例?顺便提一下,我用AD登录名和密码以及代码成功实现了Windows身份验证。

string userName = HttpContext.User.Identity.Name.Split('\\')[1].ToString();

显示正确的用户。我还尝试操作对象类型[DirectoryObjectClass("user")],但没有任何结果。

【问题讨论】:

  • 我检查过 if (null == UserPrincipalExtended.FindByIdentity(new PrincipalContext(ContextType.Domain), User.Identity.Name)) { throw new Exception("Some exception"); } 但异常仍然发生

标签: c# asp.net asp.net-mvc asp.net-mvc-4 active-directory


【解决方案1】:

首先,我建议将您的PrincipalContext 放入using() { ... }? 块中,以确保妥善处理。

另外:每当您调用进入例如的方法时Active Directory(或数据库,或调用 Web 服务) - 那么您需要确保您实际上得到了有效的东西!不要只是盲目地假设调用成功 - 也许它成功了 - 也许它没有 - 检查成功!

所以我会这样写这个索引方法:

public async Task<ActionResult> Index()
{          
    using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
    {
        UserPrincipalExtended user = UserPrincipalExtended.FindByIdentity(ctx, User.Identity.Name);          

        // check FOR NULL ! 
        // Defensive programming 101 - ALWAYS check, NEVER just assume!
        if (user != null) 
        {
            var title = user.Title;        
            ViewBag.Message = title;
        }
        else 
        {
            // handle the case that NO user was found !
            ViewBag.Message = "(no user found)";
        }
    }

    return View();
}

【讨论】:

  • 谢谢,但没有结果。
  • 我明白了!对于那些有类似问题的人,您需要这样放置用户对象: using (HostingEnvironment.Impersonate()) { UserPrincipal user = UserPrincipal.FindByIdentity(new PrincipalContext(ContextType.Domain), User.Identity.Name);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-29
  • 1970-01-01
  • 1970-01-01
  • 2014-04-07
  • 1970-01-01
  • 2013-11-28
相关资源
最近更新 更多