首页 > 解决方案 > 在用作委托的静态方法中访问 DbContext

问题描述

我正在为 .net core web api 实现一个身份验证提供程序。“auth”的东西在一个单独的项目中,并且有一个主项目的委托。此委托用于从公共访问 ID 中检索“秘密”。

public delegate string RetrievePrivateKey(string publicKey);

这是在 Startup.cs 文件中设置的,如下所示: options.GetPrivateKey += Utilities.APIAccess.GetPrivateKeyFromPublic;

我的问题是该方法需要数据库上下文才能进行查找。实现这一目标的最佳方法是什么?DbContext 是一个 mysql 上下文,通过 appsettings.json 设置连接字符串。在大多数情况下,一切都是 DI。

作为参考,“GetPrivateKeyFromPublic”方法如下所示:

//This does not work, as it isn't grabbing the options/etc.  Was just trying various things I read.
public static string GetPrivateKeyFromPublic(string publicKey)
        {
            DbContextOptions<DirectionsContext> options = new DbContextOptions<DirectionsContext>();
            DirectionsContext ctx = new DirectionsContext(options);
            DeviceService service = new DeviceService(ctx);
            if (publicKey == "<default public>")//testing
                return "<default private>";//testing
            return service.GetPrivateKeyFromPublicKey(publicKey);
        }

启动.cs

public void ConfigureServices(IServiceCollection services)
        {
            services.AddRazorPages();
            services.AddControllers();
            services.AddDbContext<DirectionsContext>(options => options.UseMySql(Configuration.GetConnectionString("Development")));
            services.AddMemoryCache();
            services.AddSingleton<HmacHandler>();
            services.AddSingleton<HmacOptions>();
            services.AddAuthentication(App.Security.HmacDefaults.AuthenticationScheme).AddHmac(options =>
            {
                options.AuthName = "HMAC-SHA256";
                options.CipherStrength = HmacCipherStrength.Hmac256;
                options.EnableNonce = true;
                options.EnableDeviceOS = true;
                options.RequestTimeLimit = 5;
                options.GetPrivateKey += Utilities.APIAccess.GetPrivateKeyFromPublic;
                options.GetDeviceOS += Utilities.DeviceIdentify.GetDeviceOSFromUserAgent;//Utilities.DeviceUtility.GetDeviceOSFromUserAgent;
            });

标签: c#asp.net-coreasp.net-web-api

解决方案


正如我在评论中所说,我基本上做了以下事情:

我在 HmacOptions 中设置了一个通用的 DbContext 对象。然后通过 Startup.cs 中的 ConfigureServices() 方法传入。

services.AddAuthentication(Directions.App.Security.HmacDefaults.AuthenticationScheme).AddHmac(options =>
            {
                options.AuthName = "HMAC-SHA256";
                options.CipherStrength = HmacCipherStrength.Hmac256;
                options.EnableNonce = true;
                options.EnableDeviceOS = true;
                options.RequestTimeLimit = 5;
                options._Context = context;
                options.GetPrivateKey += Utilities.APIAccess.GetPrivateKeyFromPublic;
                options.GetDeviceOS += Utilities.DeviceIdentify.GetDeviceOSFromUserAgent;
            });

然后在 auth 库中使用通用 db 上下文。


推荐阅读