Calling service/repository methods in ASP.Net Core middleware

ぐ巨炮叔叔 提交于 2019-12-05 16:30:53

To use scoped dependencies in a middleware (which is necessarily a singleton by definition), the best approach is to flow it as a parameter of InvokeAsync instead of flowing it via the constructor:

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" });
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!