我已经使用组件实现了这个解决方案,但这似乎有点过头了。
Views\Shared_LoginPartial.cshtml
...
@await Component.InvokeAsync("FirstName", User.Identity.GetUserId())
...
Views\Shared\Components\FirstName\Default.cshtml
@model Models.ApplicationUser
@Html.ActionLink("Hello " + Model.FirstName + "!", "Manage", "Account", routeValues: null, htmlAttributes: new { title = "Manage" })
ViewComponents\FirstNameViewComponent.cs
public class FirstNameViewComponent : ViewComponent
{
private readonly IUserService m_userService;
public FirstNameViewComponent(IUserService userService)
{
m_userService = userService;
}
public async Task<IViewComponentResult> InvokeAsync(string userId)
{
Models.ApplicationUser user = await m_userService.FindUserByIdAsync(userId);
return View(user);
}
}
Services\UserService.cs
public interface IUserService
{
Task<ApplicationUser> FindUserByIdAsync(string id);
}
public class UserService : IUserService
{
private readonly UserManager<ApplicationUser> m_userManager;
public UserService(UserManager<ApplicationUser> userManager)
{
m_userManager = userManager;
}
public Task<ApplicationUser> FindUserByIdAsync(string id)
{
return m_userManager.FindByIdAsync(id);
}
}
Startup.cs
...
services.AddScoped<IUserService, UserService>();
...
我想我可以在登录后更新用户服务并存储 ApplicationUser,并在注销后将其删除,但我想知道是否有其他方法可以解决这个问题。此外,我不确定范围服务是否是这里最好的,我没有找到使它成为会话的方法,而不是请求范围。