我想在工作中使应用程序现代化,将Winforms更改为Blazor Server Side。当我尝试访问PrincipalContext 时
public UserActiveDirectory(string login, string pass)
{
_adConnection = new PrincipalContext(ContextType.Domain, ADRESSE_AD, login, pass);
}
出现FileNotFoundException"无法加载文件或程序集"System.DirectoryServices.AccountManagement"我在文档上找到了这篇文章。Microsoft:文章应用程序应该能够显示组,可以在组中添加用户,删除,。。。我认为WMI(Windows Management Instrumentation(也有同样的问题。如果有人有建议,请提供帖子链接。谢谢你的帮助。
我花了很多时间试图弄清楚如何使用Windows身份验证获取当前用户的电子邮件地址-Net Blazor服务器应用程序。试图使用索赔是一条死胡同。如上所述,System.DirectoryServices.AccountManagement就是解决方案。首先,必须使用NuGet软件包管理器安装该软件包。然后,这个Blazor页面代码可能会帮助你:
@page "/test"
@inject AuthenticationStateProvider AuthenticationStateProvider
@using System.DirectoryServices.AccountManagement
<h3>App User Data</h3>
<button @onclick="GetData">Get User Data</button>
<p>@authMessage</p>
<p>@surnameMessage</p>
<p>@emailMessage</p>
@code {
private string authMessage;
private string surnameMessage;
private string emailMessage;
private async Task GetData()
{
var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
var user = authState.User;
if (user.Identity.IsAuthenticated)
{
authMessage = $"{user.Identity.Name} is authenticated.";
var context = new PrincipalContext(ContextType.Domain);
var principal = UserPrincipal.FindByIdentity(context, user.Identity.Name);
surnameMessage = principal.Surname;
emailMessage = principal.EmailAddress;
}
else
{
authMessage = "The user is NOT authenticated.";
}
}
}
另外,在我的服务课上,我有以下内容。#pragma注释停止了警告,即这只适用于Windows服务器。
using Microsoft.AspNetCore.Components.Authorization;
using System.DirectoryServices.AccountManagement;
etc
namespace PharmacyCT.Data
{
public class ExportFileService : IExportFileService
{
private readonly string _conn;
private readonly AuthenticationStateProvider _auth;
private readonly IConfiguration _config;
public ExportFileService(IConfiguration config, AuthenticationStateProvider auth)
{
_conn = config.GetConnectionString("PharmCTConn");
_auth = auth;
_config = config;
}
public async Task<string> GetUserEmail()
{
var authState = await _auth.GetAuthenticationStateAsync();
var user = authState.User;
#pragma warning disable CA1416 // Validate platform compatibility
var context = new PrincipalContext(ContextType.Domain);
var principal = UserPrincipal.FindByIdentity(context, user.Identity.Name);
return principal.EmailAddress;
#pragma warning restore CA1416 // Validate platform compatibility
}
安装包System.DirectoryServices.AccountManagement