在docker中运行的ASP.NET核心服务不响应API请求

jslywgbw  于 2023-08-08  发布在  .NET
关注(0)|答案(1)|浏览(104)

我有一个奇怪的问题,我的.net应用程序试图运行它与docker-compose。当我调试我的应用程序时,我可以看到日志,并且根本没有显示任何错误,它表明应用程序正在X端口上运行。但是当我去swagger甚至tho它显示正确的所有我的控制器端点时,我想提出一个请求什么也没有发生,只停留在“加载”。
这是我的程序.cs:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddTransient<TokenValidationMiddleware>();
builder.Services.AddHttpClient();
builder.Services.AddStackExchangeRedisCache(r =>
{
    r.Configuration = builder.Configuration["redis:connectionString"];
});

builder.Services.AddCors();
builder.Services.AddScoped<IUserContext, UserContext>();
builder.Services.AddControllers()
    .AddJsonOptions(options =>
    {
        options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
    });

builder.Services.AddDbContext<ApplicationDbContext>(options =>
{
    options.UseSqlServer(builder.Configuration.GetConnectionString("ConnectionString")).UseLazyLoadingProxies();
});

builder.Services.AddIdentityCore<ApplicationUser>(opt =>
{
    opt.Password.RequireNonAlphanumeric = false;
})
    .AddRoles<ApplicationRole>()
    .AddRoleManager<RoleManager<ApplicationRole>>()
    .AddSignInManager<SignInManager<ApplicationUser>>()
    .AddRoleValidator<RoleValidator<ApplicationRole>>()
    .AddEntityFrameworkStores<ApplicationDbContext>();

builder.Services.AddRouting(options =>
{
    options.LowercaseUrls = true;
    options.LowercaseQueryStrings = true;
});

builder.Services.AddSingleton<SymmetricSecurityKey>(provider =>
{
    return new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]!));
});

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(...
            });

builder.Services.AddAuthorization(opt =>
{
});

builder.Services.AddScoped<IDbInitializer, DbInitializer>();

builder.Services.AddAutoMapper(x => x.AddMaps(Assembly.GetExecutingAssembly()));

builder.Services.AddScoped(provider => new MapperConfiguration(cfg =>
{
    cfg.AddProfile(new AutoMapperProfiles(provider.GetService<ITokenService>()!));
}).CreateMapper());

// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "web server api", Version = "v1" });
    c.SchemaFilter<EnumSchemaFilter>();
});

builder.Services.AddHttpContextAccessor();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
    app.UseCors(builder =>
    {
        builder.AllowAnyOrigin();
        builder.AllowAnyMethod();
        builder.AllowAnyHeader();
    });
}

app.UseHttpsRedirection();
app.UseRouting();

app.UseAuthentication();
app.UseMiddleware<TokenValidationMiddleware>();
app.UseAuthorization();

app.MapControllers();

using (var scope = app.Services.CreateScope())
{
    var dbInitializer = scope.ServiceProvider.GetRequiredService<IDbInitializer>();
    dbInitializer.Initialize();
}

app.Run();

字符串
DockerFile:

#See https://aka.ms/containerfastmode to understand how Visual Studio uses this Dockerfile to build your images for faster debugging.

FROM mcr.microsoft.com/dotnet/aspnet:7.0 AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443

FROM mcr.microsoft.com/dotnet/sdk:7.0 AS build
WORKDIR /src
COPY ["proj.csproj", "."]
RUN dotnet restore "./proj.csproj"
COPY . .
WORKDIR "/src/."
RUN dotnet build "proj.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "proj.csproj" -c Release -o /app/publish /p:UseAppHost=false

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "proj.dll"]


docker-compose-override.yml:

version: '3.4'

services:
  tokendb:
    container_name: tokendb
    restart: always
    ports:
      - "6379:6379"
      
  db:
    container_name: sqlserver
    environment: 
      ACCEPT_EULA: 'Y'
      MSSQL_SA_PASSWORD: 'Test'
      MSSQL_PID: 'Developer'
      MSSQL_USER: 'test'
    restart: always
    ports:
      - '1433:1433'
      
  proj:
    environment:
      - ASPNETCORE_ENVIRONMENT=Development
      - "ConnectionStrings__ConnectionString=Server=db;Database=db;User Id=test;Password=Test;MultipleActiveResultSets=true;TrustServerCertificate=true"
      - "redis__connectionString=tokendb"
    depends_on:
      - db
      - tokendb
    ports:
      - "8002:80"


launchsettings.json:

{
  "profiles": {
    "Docker": {
      "commandName": "Docker",
      "launchBrowser": true,
      "launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}/swagger",
      "publishAllPorts": true,
      "useSSL": true
    }
  }
}


docker日志:

warn: Microsoft.AspNetCore.DataProtection.Repositories.FileSystemXmlRepository[60]
      Storing keys in a directory '/root/.aspnet/DataProtection-Keys' that may not be persisted outside of the container. Protected data will be unavailable when container is destroyed.
warn: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[35]
      No XML encryptor configured. Key {f90133af-ea02-45ca-bc10-878b34233e36} may be persisted to storage in unencrypted form.
info: Microsoft.Hosting.Lifetime[14]
      Now listening on: http://[::]:80
info: Microsoft.Hosting.Lifetime[0]
      Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
      Hosting environment: Development
info: Microsoft.Hosting.Lifetime[0]
      Content root path: /app

pkwftd7m

pkwftd7m1#

我发现了这个问题(尽管有点奇怪,.net没有引发任何异常)。
问题是:

  • IAccountService正在注入IMapper
  • 我有一个配置文件注入了ITokenService
  • ITokenService正在注入IAccountService

然后在我的AccountController中,我注入了AccountService,这导致请求只停留在“Loading”中。

相关问题