System.InvalidOperationException:无法解析作用域服务 - .NET 6

问题描述 投票:0回答:1

我刚刚将中间件添加到我的代码中,当我想运行它时出现此错误

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();

感谢对此的任何帮助。谢谢

编辑添加:

异常的完整细节

System.InvalidOperationException HResult=0x80131509 Message=无法解析来自根提供商的作用域服务“HORA_API.Model.AGUSContext”。 源=Microsoft.Extensions.DependencyInjection 堆栈跟踪: 在 Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteValidator.ValidateResolution(类型 serviceType、IServiceScope 范围、IServiceScope rootScope) 在 Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(类型 serviceType,ServiceProviderEngineScope serviceProviderEngineScope) 在 Microsoft.Extensions.Internal.ActivatorUtilities.ConstructorMatcher.CreateInstance(IServiceProvider 提供商) 在 Microsoft.Extensions.Internal.ActivatorUtilities.CreateInstance(IServiceProvider 提供程序,类型 instanceType,对象 [] 参数) 在 Microsoft.AspNetCore.Builder.UseMiddlewareExtensions.<>c__DisplayClass5_0.b__0(接下来是 RequestDelegate) 在 Microsoft.AspNetCore.Builder.ApplicationBuilder.Build() 在 Microsoft.AspNetCore.Builder.WebApplicationBuilder.b__27_0(接下来是 RequestDelegate) 在 Microsoft.AspNetCore.Builder.ApplicationBuilder.Build() 在 Microsoft.AspNetCore.Hosting.GenericWebHostService.d__37.MoveNext() 在 Microsoft.Extensions.Hosting.Internal.Host.d__12.MoveNext() 在 Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.d__4.MoveNext() 在 Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.d__4.MoveNext() 在 Microsoft.Extensions.Hosting.HostingAbstractionsHostExtensions.Run(IHost 主机) 在 Microsoft.AspNetCore.Builder.WebApplication.Run(字符串 url) 在 C:\Hora 中的 Program.$(String[] args) 与 090123 pi\HORA-API\HORA-API\Program.cs:line 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);
    }
c# asp.net asp.net-mvc middleware asp.net-core-6.0
1个回答
0
投票

注入中间件将从根生命周期解决它,它无权访问范围。 改为从上下文提供者解析它,它可以访问范围

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);
}
© www.soinside.com 2019 - 2024. All rights reserved.