4

What is the best way to model the current user in a query? I'm creating a razor page application. I need to be able to attach the current user when I am executing queries and commands. Is there a recommended approach for doing this?

4

1 回答 1

12

下面的方法对我很有效,因为我让用户进入了我的 Razor 项目所依赖的服务层。

根据 David Fowler here的指导,我创建了一个UserAccessor类,如下所示:

public class UserAccessor : IUserAccessor
{
    private readonly IHttpContextAccessor _accessor;

    public UserAccessor(IHttpContextAccessor accessor)
    {
        _accessor = accessor ?? throw new ArgumentNullException(nameof(accessor));
    }

    public ClaimsPrincipal User => _accessor.HttpContext.User;
}

我在启动时通过调用在我的 Razor 项目中注册

services.AddTransient<IUserAccessor, UserAccessor>()

然后根据需要将其注入 MediatR 处理程序和我的 DbContext 以及一些工厂。

private readonly IUserAccessor _userAccessor;

public EventLogFactory(IUserAccessor userAccessor)
{
    _userAccessor = userAccessor ?? throw new ArgumentNullException(nameof(userAccessor));
} 

在不引用Microsoft.AspNetCore.AppIHttpContextAccessor元包的项目中引用的UserAccessor需要Microsoft.AspNetCore.Http.Abstractions nuget,并且还需要在启动时实现 Razor 项目:AddHttpContextAccessor()

// Register IHttpContextAccessor for services to get access to the HttpContext.  
services.AddHttpContextAccessor();

希望这可以帮助。

于 2018-10-23T19:16:23.143 回答