在Blazor组件中获取当前用户 [英] Get Current User in a Blazor component

查看:482
本文介绍了在Blazor组件中获取当前用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Blazor和Windows身份验证来启动一个新站点,并且需要标识正在查看页面/组件的当前用户.

I'm starting a new site with Blazor and Windows Authentication and need to identify the current user viewing the page/component.

对于Razor页面,可以使用Context.User.Identity.Name访问当前用户名,但是在Blazor组件中似乎不起作用.我尝试将HttpContext注入组件,但是在运行时Context为null.

For a Razor Page, the current user name can be accessed with Context.User.Identity.Name, but that doesn't seem to work in a Blazor component. I've tried injecting HttpContext into the component but the Context is null at runtime.

作为奖励,我最终希望将其合并到Startup.cs中,因此我只需要获取一次用户名,就可以在我的应用程序中使用企业用户类(使用EF Core).针对该用例量身定制的答案也将不胜感激.

As a bonus, I will eventually want to incorporate this into Startup.cs so I only need to get the username once and can leverage a corporate user class (with EF Core) for my applications. Answers tailored to that use case would also be appreciated.

推荐答案

我现在已经能够将其与通用类以及组件一起使用.

I've now been able to get it to work with a general class, as well as a component.

获得对HttpContext用户的访问权限;在ConfigureServices的Startup.cs中添加

To get access to the HttpContext User; in ConfigureServices, in Startup.cs add

services.AddHttpContextAccessor();

我的CorporateUser类有CorporateUserService类.服务类通过构造函数注入获得DbContext.

I have a CorporateUserService class for my CorporateUser class. The service class gets a DbContext through constructor injection.

然后,我创建了一个新的CurrentCorporateUserService,它继承自CorporateUserService.它通过构造函数注入接受DbContext和IHttpContextAccessor

I then created a new CurrentCorporateUserService that inherits from the CorporateUserService. It accepts a DbContext and an IHttpContextAccessor through constructor injection

public class CurrentCorporateUserService : CorporateUserService
{
    private readonly IHttpContextAccessor _httpContextAccessor;

    public CurrentCorporateUserService(IHttpContextAccessor httpContextAccessor, MyDbContext context) : base(context)
    {
        _httpContextAccessor = httpContextAccessor;
    }
    ...

基本服务类具有方法GetUserByUsername(string username).当前服务类添加了其他方法

The base service class has a method GetUserByUsername(string username). The Current service class adds an additional method

public CorporateUser GetCurrentUser()
{
    return base.GetUserByUsername(_httpContextAccessor.HttpContext.User.Identity.Name.Substring(8));
}

当前服务类已在Startup.cs中注册

The Current service class is registered in Startup.cs

services.AddScoped<CurrentCorporateUserService>();

完成后,我可以在带有指令注入的组件中使用CurrentCorporateUserService.

Once that is done, I can use the CurrentCorporateUserService in a component with directive injection.

    [Inject]
    private CurrentCorporateUserService CurrentCorporateUserService { get; set; } = 
    default!;

或在任何带有构造函数注入的类中.

or in any class, with constructor injection.

    public MyDbContext( DbContextOptions<MyDbContext> options
                  , CurrentCorporateUserService CurrentCorporateUserService )
                  : base(options) 
    {
        _currentUser = CurrentCorporateUserService.GetCurrentUser();
    }

为它提供项目范围的服务意味着我所有的开发人员都不必担心如何获取当前用户,他们只需要将服务注入其类中即可.

Making it a project wide service means all my developers do not have to concern themselves with how to get the Current User, they just need to inject the service into their class.

例如,在MyDbContext中使用它可使当前用户可用于每个保存事件.在下面的代码中,保存记录的所有继承BaseReport类的类都会自动更新报告元数据.

For example, using it in MyDbContext makes the current user available to every save event. In the code below, any class that inherits the BaseReport class will automatically have the report metadata updated when the record is saved.

public override Int32 SaveChanges()
{         
    var entries = ChangeTracker.Entries().Where(e => e.Entity is BaseReport
    && (e.State == EntityState.Added || e.State == EntityState.Modified));

            foreach (var entityEntry in entries)
            {
                ((BaseReport)entityEntry.Entity).ModifiedDate = DateTime.Now;
                ((BaseReport)entityEntry.Entity).ModifiedByUser = _currentUser.Username;

            }

    return base.SaveChanges();
}

这篇关于在Blazor组件中获取当前用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆