簡體   English   中英

ASP.NET MVC4中的Active Directory字段-未處理的異常

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

我需要實現一個從AD檢索某些字段的類。 我遵循了這里的指示: link 但是我從line得到了一個未處理的異常:

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")]但沒有任何結果。

首先,我建議將您的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();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM