简体   繁体   English

ASP.NET MVC4中的Active Directory字段-未处理的异常

[英]Active Directory fields in ASP.NET MVC4 - unhandled exception

I need to implement a class which retrieves some fields from AD. 我需要实现一个从AD检索某些字段的类。 I've followed the instruction from here: link . 我遵循了这里的指示: link But I get an unhandled exception from line : 但是我从line得到了一个未处理的异常:

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

My controller code looks like this: 我的控制器代码如下所示:

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();
   }

Should I add any additional configuration? 我应该添加任何其他配置吗? In web.config for example? web.config为例? I'd like to mention that I successfully implement Windows authentication with AD login and password and the code. 我想提到的是,我成功地通过AD登录名和密码以及代码来实现Windows身份验证。

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

shows right user. 显示正确的用户。 Also I've tried to manipulate an object type [DirectoryObjectClass("user")] but without any result. 我也尝试操纵对象类型[DirectoryObjectClass("user")]但没有任何结果。

First of all, I would recommend putting your PrincipalContext into a using() { ... }? 首先,我建议将您的PrincipalContext放入using() { ... }? block to ensure proper disposal. 阻止以确保正确处置。

Also: whenever you call a method that goes into eg Active Directory (or a database, or calls a web service) - then you need to ensure that you're actually getting back something valid! 另外:每当您调用进入Active Directory(或数据库,或调用Web服务)的方法时-您都需要确保您实际上已经获得了有效的东西! Don't just blindly assume the call succeeded - maybe it did - maybe it didn't - check for success! 不要只是盲目地假设呼叫成功-也许成功-也许没有- 检查成功!

So I would write this index method like this: 所以我会这样写这个索引方法:

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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM