【问题标题】:Calling service/repository methods in ASP.Net Core middleware在 ASP.Net Core 中间件中调用服务/存储库方法
【发布时间】:2016-05-10 14:59:14
【问题描述】:

这里是 ASP.Net Core 菜鸟...我正在使用一个 ASP.Net Core WebAPI 核心项目,该项目使用带有 EF 6 的 DNX451。

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

这是实现查看上下文并获取 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);
    }
}

回购

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;
    }
}

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

在创建模型时不能使用上下文。这 如果在内部使用上下文可能会引发异常 OnModelCreating 方法,或者如果相同的上下文实例被访问 多个线程同时进行。注意 DbContext 的实例成员 和相关的类不保证是线程安全的。

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

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

【问题讨论】:

    标签: entity-framework-6 asp.net-web-api2 asp.net-core


    【解决方案1】:

    要在中间件中使用作用域依赖项(根据定义,它必须是单例),最好的方法是将其作为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" });
        }
    }
    

    【讨论】:

    • 谢谢!这正是我所需要的。
    • 非常感谢!我没有意识到我可以将 DI 与 Invoke 方法一起使用。它解决了我使用相同上下文的 2 个并发请求的问题。
    猜你喜欢
    • 2019-04-07
    • 1970-01-01
    • 1970-01-01
    • 2016-11-05
    • 2018-06-22
    • 2016-10-25
    • 1970-01-01
    • 2011-05-21
    相关资源
    最近更新 更多