c# - 在用作委托的静态方法中访问 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;
});
解决方案
正如我在评论中所说,我基本上做了以下事情:
我在 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 上下文。
推荐阅读
- google-classroom - 如何获取 Google Classroom API 的课程 ID
- c++ - 使用 C++ 的矩阵乘法
- aws-cdk - CfnNetworkInterface 中的网络接口错误
- c# - SmtpClient 不适用于构造函数中给出的值
- python - 无法使用正则表达式删除不需要的项目
- exception - ESP8266 反复抛出 Exception(0)
- raspberry-pi - 如何向连接到树莓派的 GPS 模块发送 AT 命令
- docker - Docker 中的 Dotnet 在 linux 上发布错误(Azure DevOps 构建)
- java - 如何在本地使用 spring-cloud-starter-aws 运行应用程序?
- linux - 目标与目标模式不匹配