C# ASP.NET MVC4中的Active Directory字段-未处理的异常
我需要实现一个从AD中检索某些字段的类。我遵循了以下说明:。但我从第行收到一个未处理的异常:C# ASP.NET MVC4中的Active Directory字段-未处理的异常,c#,asp.net,asp.net-mvc,asp.net-mvc-4,active-directory,C#,Asp.net,Asp.net Mvc,Asp.net Mvc 4,Active Directory,我需要实现一个从AD中检索某些字段的类。我遵循了以下说明:。但我从第行收到一个未处理的异常: return (UserPrincipalExtended)FindByIdentityWithType(context, typeof(UserPrincipalExtended), identityValue) 我的控制器代码如下所示: using System.Threading.Tasks; using System.Net; using System.Data.Entity; using S
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();
}
显示正确的用户。此外,我还尝试操作对象类型[DirectoryObjectClassuser],但没有任何结果。首先,我建议将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();
}
我已经检查过null==UserPrincipalExtend.FindByIdentity new PrincipalContextContextType.Domain,User.Identity.Name{抛出新的异常some exception;}但异常仍然发生谢谢,但没有结果。我明白了!对于那些有类似问题的用户,您需要像这样放置用户对象:使用HostingEnvironment.Impersonate{UserPrincipal user=UserPrincipal.FindByIdentitynew PrincipalContextContextType.Domain,user.Identity.Name;
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();
}