asp.net 系统操作无效异常:无法解析作用域服务- .NET 6

wz8daaqr  于 2023-03-09  发布在  .NET
关注(0)|答案(1)|浏览(183)

我刚刚将中间件添加到我的代码中,当我想运行它时,它会出现此错误
System.InvalidOperationException: 'Cannot resolve scoped service 'HORA_API.Model.AGUSContext' from root provider.'

这是程序. cs

global using HORA_API.Model;
using HORA_API.Middleware;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddDbContext<AGUSContext>();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

 //app.UseAuthorization();
app.UseMiddleware<JwtMiddleware>();

app.MapControllers();

app.Run();

感谢你的帮助谢谢
编辑以添加:
异常的完整详细信息
系统操作无效异常HResult= 0x 80131509消息=无法从根提供程序解析作用域服务“HORA_API.Model.AGUSContext”。源=Microsoft.Extensions.DependencyInjection堆栈跟踪:在Microsoft.扩展.依赖注入.服务查找.调用站点验证器.验证解决方案(类型服务类型、IServiceScope作用域、IServiceScope根作用域)。扩展。依赖关系注入。服务提供程序。获取服务(在Microsoft中键入服务类型、服务提供商工程范围服务提供商工程范围)。扩展。内部。激活器实用程序。构造器匹配器。创建示例(IServiceProvider提供程序)。扩展。内部。激活器实用程序。创建示例(IServiceProvider提供程序,类型示例类型,对象[]参数)。〈〉c__DisplayClass5_0.b__0(接下来是请求委托),位于Microsoft.AspNetCore.Builder. Application Builder.Build(),位于Microsoft. AspNetCore.生成器. Web应用程序生成器. b__27_0(接下来是请求委托),位于Microsoft.AspNetCore.Builder. Application Builder.Build(),位于Microsoft. AspNetCore.主机.通用Web主机服务. d__37.下一步(),位于Microsoft.扩展.主机.内部.主机.d__12.下一步()位于Microsoft.扩展.主机.主机抽象主机扩展. d__4.下一步()位于Microsoft.扩展.主机.主机抽象主机扩展. d__4.下一步()在Microsoft.扩展.托管.托管抽象主机扩展.运行(IHost主机)在Microsoft.AspNetCore.Builder. Web应用程序.运行(字符串url)在C中的程序.$(字符串[]参数):\Hora vs 090123\API\HORA-API\HORA-API\程序.cs:第30行
中间件代码

public async Task Invoke(HttpContext context, AGUSContext dataService)
{
    var token = context.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last();

    if (token != null)
        attachUserToContext(context, dataService, token);

    await _next(context);
}

private void attachUserToContext(HttpContext context, AGUSContext dataService, string token)
{
    try
    {
        var tokenHandler = new JwtSecurityTokenHandler();
        var key = Encoding.ASCII.GetBytes("SecretToken");
        tokenHandler.ValidateToken(token, new TokenValidationParameters
        {
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(key),
            ValidateIssuer = false,
            ValidateAudience = false,
            // set clockskew to zero so tokens expire exactly at token expiration time (instead of 5 minutes later)
            ClockSkew = TimeSpan.Zero
        }, out SecurityToken validatedToken);

        var jwtToken = (JwtSecurityToken)validatedToken;
        var email = jwtToken.Claims.First(x => x.Type == "id").Value;

        // attach user to context on successful jwt validation
        var useremail = dataService.Otps.FirstOrDefault(v => v.AlamatEmail == email);
        if (useremail != null)
        {
            context.Items["User"] = "Ok";
        }
    }
    catch
    {
        // do nothing if jwt validation fails
        // user is not attached to context so request won't have access to secure routes
    }

属性授权

public void OnAuthorization(AuthorizationFilterContext context)
{
    if (context.HttpContext.Items["User"] == null)
    {
        // not logged in
        context.Result = new JsonResult(new { message = "Unauthorized" }) { StatusCode = StatusCodes.Status401Unauthorized };
    }
}

然后我在控制器上加了这个

private string generateJwtToken(string email)
    {
        // generate token that is valid for 7 days
        var tokenHandler = new JwtSecurityTokenHandler();
        var key = Encoding.ASCII.GetBytes(otpcode);
        var tokenDescriptor = new SecurityTokenDescriptor
        {
            Subject = new ClaimsIdentity(new[] { new Claim("id", email) }),
            Expires = DateTime.UtcNow.AddDays(1),
            SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
        };
        var token = tokenHandler.CreateToken(tokenDescriptor);
        return tokenHandler.WriteToken(token);
    }
9gm1akwq

9gm1akwq1#

注入中间件将从根生存期解析它,因为它没有访问范围的权限。请从上下文提供者解析它,因为它可以访问范围

public async Task Invoke(HttpContext context)
{
    // Resolve the context
    var dataService = context.RequestServices.GetRequiredService<AGUSContext>();
    var token = context.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last();

    if (token != null)
        attachUserToContext(context, dataService, token);

    await _next(context);
}

相关问题