使用用户电子邮件更新公共字段 [英] Updating common field with user email

查看:114
本文介绍了使用用户电子邮件更新公共字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找出授权用户当前正在尝试保存数据并记录其电子邮件的内容.

I am trying to find out what the authorized user is currently trying to save the data and record their email.

我在dbcontext中有一个基本设置,可以进行时间戳的更新,但是我不知道如何访问用户信息:

I have a basic setup in my dbcontext that does the update for timestamps but i cannot figure out how to access the user information:

    public override int SaveChanges()
{
    AddTimestamps();
    return base.SaveChanges();
}


public override async Task<int> SaveChangesAsync()
        {
            AddTimestamps();
            return await base.SaveChangesAsync();
        }

    private void AddTimestamps()
    {
        var entities = ChangeTracker.Entries()
            .Where(x => x.State == EntityState.Added || x.State == EntityState.Modified);

        var currentUser = "dumm@dummy.com" // This i haven't been able to figure out how to retrieve

        foreach (var entity in entities)
        {
            if (entity.State == EntityState.Added)
            {
                ((BaseEntity)entity.Entity).DateCreated = DateTime.UtcNow;
                ((BaseEntity)entity.Entity).CreatedBy = currentUsername;
            }

            ((BaseEntity)entity.Entity).DateModified = DateTime.UtcNow;
            ((BaseEntity)entity.Entity).ModifiedBy = currentUsername;
        }
    }
}

更多背景知识全部基于ASP Core 2和EF Core构建. DBContext位于我的APIContoso项目中,该项目利用名为IDPContoso的自定义身份提供程序,该提供程序基于ASP Core 2和Identity Server4构建.

Bit more of a background this is all built on ASP Core 2 and EF Core. The DBContext is located in my APIContoso project, which utilises the custom Identity Provider called IDPContoso which is built on ASP Core 2 and Identity Server4.

如何在DBContext中获取用户电子邮件,以便对其进行记录?

How can I obtain the users email within the DBContext so i can record it?

推荐答案

我建议您从身份信息中获取电子邮件.这样,您无需额外调用数据库.如果您使用电子邮件登录,则User.Identity.Name包含电子邮件(如果映射正确).否则,添加包含电子邮件的声明.

I suggest you get the email from the identity. This way you don't need an extra call to the database. If you are using the email to login then User.Identity.Name contains the email (if mapped correctly). Otherwise add a claim that contains the email.

现在,您需要将电子邮件注入模型.我为模型假设了一个单独的项目.在这种情况下,您不能只注入IHttpContextAccessor.否则,您可以简单地注入IHttpContextAccessor并在构建模型时读取用户信息.

Now you'll need to inject the email into the model. I assume a seperated project for the model. In that case you cannot just inject IHttpContextAccessor. Otherwise you can simply inject IHttpContextAccessor and read the user info when the model is constructed.

以下代码仅用于演示目的.在Startup.cs中注入一个包含connectionInfo的对象:

The following code is for demonstration purposes only. In Startup.cs inject an object that contains the connectionInfo:

public void ConfigureServices(IServiceCollection services)
{
    services.AddScoped(provider => new Database.ConnectionInfo
    {
        ConnectionString = provider.GetRequiredService<ApplicationSettings>().ConnectionString,
        User = provider.GetRequiredService<IHttpContextAccessor>().HttpContext.User?.Identity.Name
    });
    services.AddScoped<Model>();
}

因为这是作用域,所以每次用户连接时,都会设置用户信息.对于匿名用户,User = null.请注意,模型本身也是作用域的. connectionInfo类:

Because this is scoped, every time a user connects, the user information is set. For anonymous users, User = null. Notice that the model itself is also scoped. The connectionInfo class:

public class ConnectionInfo
{
    public string ConnectionString { get; set; }
    public string User { get; set; }
}

现在在Model中,您具有以下构造函数:

Now in Model you have the following constructor:

private string _user { get; }

public Model(ConnectionInfo connection)
    : base(connection.ConnectionString)
{
    _user = connection.User;
}


private void AddTimestamps()
{
    var entities = ChangeTracker.Entries()
        .Where(x => x.State == EntityState.Added || x.State == EntityState.Modified);

    var currentUser = _user;
}

这篇关于使用用户电子邮件更新公共字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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