Base solution for your next web application
Open Closed

Get UserID during configure of DbContextConfigurer to inject user ID into SQL session context #8991


User avatar
0
alexmann_petal created

We are trying to use RLS on a second database connection (not the abp DB). To get the RLS to work we need to inject a session context to the SQL procedure call each time entity framework calls the database. The session context we want to inject is the username (or UserID it doesn’t really matter which).
We are able to inject the session context using the below code in the DbContextConfigurer

public class PETALDataDbContextConfigurer: ITransientDependency
{
        private static SqlConnection connection;

public static void Configure(DbContextOptionsBuilder<PETALDataDbContext> builder, string connectionString)
        {

            connection = new SqlConnection(connectionString);
            connection.StateChange += Connection_StateChange;

            builder.UseSqlServer(connection);
        }

public static void Configure(DbContextOptionsBuilder<PETALDataDbContext> builder, DbConnection connection)
        {
            builder.UseSqlServer(connection);
        }

private static void Connection_StateChange(object sender, System.Data.StateChangeEventArgs e)
        {

            var username = "need username";
            if (e.CurrentState == ConnectionState.Open)
            {
                var cmd = connection.CreateCommand();
cmd.CommandText = @"exec sp_set_session_context @key=N'Username', @value='" + username + "'";
cmd.ExecuteNonQuery();
            }
        }
}

The problem is getting the username at this point. Have referred to this documentation a lot https://aspnetboilerplate.com/Pages/Documents/Abp-Session But haven’t been able to get an instantiated AbpSession. Is there another way to get the username that will work at this point? In case its not clear from the code the name of the second database is PETALData.


2 Answer(s)
  • User Avatar
    1
    ismcagdas created
    Support Team

    Hi @alexmann_petal

    I'm not sure but below code might work;

    IocManager.Instance.Resolve<IAbpSession>();

  • User Avatar
    0
    alexmann_petal created

    @ismcagdas That worked perfectly! Thank you