是的,您可以访问数据库!在Configure
方法中运行的代码可以访问在ConfigureServices
方法中添加的任何服务,包括像数据库上下文这样的东西。
例如,如果您有一个简单的Entity Framework上下文:
using Microsoft.EntityFrameworkCore;
using SimpleTokenProvider.Test.Models;
namespace SimpleTokenProvider.Test
{
public class SimpleContext : DbContext
{
public SimpleContext(DbContextOptions<SimpleContext> options)
: base(options)
{
}
public DbSet<User> Users { get; set; }
}
}
然后在 ConfigureServices
中添加它:
services.AddDbContext<SimpleContext>(opt => opt.UseInMemoryDatabase());
然后,当您设置中间件时,可以访问它:
var context = app.ApplicationServices.GetService<SimpleContext>();
app.UseSimpleTokenProvider(new TokenProviderOptions
{
Path = "/api/token",
Audience = "ExampleAudience",
Issuer = "ExampleIssuer",
SigningCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256),
IdentityResolver = (username, password) => GetIdentity(context, username, password)
});
稍微改写一下GetIdentity
方法:
private Task<ClaimsIdentity> GetIdentity(SimpleContext context, string username, string password)
{
// Access the database using the context
// Here you'd need to do things like hash the password
// and do a lookup to see if the user + password hash exists
}
我是原始示例的作者。最初很抱歉没有表达清楚!我试图编写IdentityResolver
委托,使其易于提供自己的功能-例如与您自己的数据库集成(如上所述),或连接到ASP.NET Core Identity。当然,你也可以随意放弃我的代码并做得更好。:)
AddDbContext
,那么您的DB服务是作用域的。请查看我的答案以获取解决方案。 - Florian Moser