gpt4 book ai didi

entity-framework-6 - 在 ASP.Net Core 中间件中调用服务/存储库方法

转载 作者:行者123 更新时间:2023-12-04 23:30:41 28 4
gpt4 key购买 nike

ASP.Net Core noob 在这里......我正在使用一个使用 DNX451 和 EF 6 的 ASP.Net Core WebAPI 核心项目。

我需要在我们的服务中实现 API key 身份验证。为此,我创建了从请求中获取信息并继续进行身份验证的中间件。应该去数据库,获取匹配的 key ,然后返回并进行验证。

这是实现查看上下文并获取 APIKey 的中间件

AuthenticationHandler

public class AuthorizationHandler
{
private readonly RequestDelegate _next;
private IAuthenticationService _authenticationService;

public AuthorizationHandler(RequestDelegate next, IAuthenticationService authService)
{
_authenticationService = authService;
_next = next;
}

public async Task Invoke(HttpContext context)
{
try
{
var apiKey = context.Request.Headers["Key"];
var location = context.Request.Headers["Host"];
var locationKey = _authenticationService.GetApiKey(location);

if (apiKey == locationKey)
await _next(context);


context.Response.StatusCode = 403;
context.Response.Headers.Add("WWW-Authenticate",
new[] { "Basic" });

}
catch (Exception ex)
{
context.Response.StatusCode = 500;
context.Response.Headers.Add("WWW-Authenticate",
new[] { "Basic" });
}
}
}

这是带有上下文和中间件注册的启动类
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);


builder.AddEnvironmentVariables();
Configuration = builder.Build();
}

public IConfiguration Configuration { get; set; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped(k => new DbContext(Configuration["Data:Context:ConnectionString"]));


// Add framework services.
services.AddMvc();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();

app.UseIISPlatformHandler();

app.UseStaticFiles();

app.RegisterAuthorizationHeader();
app.RegisterAuthorization();

app.UseMvc();
}

// Entry point for the application.
public static void Main(string[] args) => WebApplication.Run<Startup>(args);
}

这里是身份验证服务
public interface IAuthenticationService
{
string GetApiKey(string location);
}

public class AuthenticationService: IAuthenticationService
{
private IApiKeyRepository _apiKeyRepository;
public AuthenticationService(IApiKeyRepository repo)
{
_apiKeyRepository= repo;
}

public string GetApiKey(string location)
{
return _apiKeyRepository.GetApiKeyByLocation(location);
}
}

repo
public interface IApiRepository
{
string GetApiKeyByLocation(string location);
}

public class ApiRepository: IApiRepository
{
private DbContext _context;

public ApiRepository(DbContext context)
{
_context = context;
}

public string GetApiKeyByLocation(string location)
{
var apiRow = _context.ApiKeyStore.FirstOrDefault(a => a.Location == location);

return apiRow == null ? string.Empty : apiRow.APIKey;
}
}

尝试此操作时,我收到以下错误:

The context cannot be used while the model is being created. This exception may be thrown if the context is used inside the OnModelCreating method or if the same context instance is accessed by multiple threads concurrently. Note that instance members of DbContext and related classes are not guaranteed to be thread safe.



现在,当我调试这个时,每个断点都会被击中两次。我相信我懂 为什么这个问题正在发生,但不知道如何解决它。

有人可以给我一个想法吗?任何更好的解决方案想法?

最佳答案

要在中间件(根据定义必须是单例)中使用作用域依赖项,最好的方法是将其作为 InvokeAsync 的参数流动。而不是通过构造函数流动它:

public async Task Invoke(HttpContext context, IAuthenticationService authenticationService)
{
try
{
var apiKey = context.Request.Headers["Key"];
var location = context.Request.Headers["Host"];
var locationKey = authenticationService.GetApiKey(location);

if (apiKey == locationKey)
await _next(context);


context.Response.StatusCode = 403;
context.Response.Headers.Add("WWW-Authenticate",
new[] { "Basic" });

}
catch (Exception ex)
{
context.Response.StatusCode = 500;
context.Response.Headers.Add("WWW-Authenticate",
new[] { "Basic" });
}
}

关于entity-framework-6 - 在 ASP.Net Core 中间件中调用服务/存储库方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37142227/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com