mathdx
mathdx

Reputation: 67

500 Error: Internal Server Error with aPI deployed on Azure with swaggwer

I deployed my API on Azure but I get a 500 error with no message! How could I solve this issue? This is my Program.cs:

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers()
    .AddJsonOptions(options =>
        options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()));
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "TangWeb_Api", Version = "v1" });
    c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
    {
        In = ParameterLocation.Header,
        Description = "Please Bearer and then token in the field",
        Name = "Authorization",
        Type = SecuritySchemeType.ApiKey
    });
    c.AddSecurityRequirement(new OpenApiSecurityRequirement {
                   {
                     new OpenApiSecurityScheme
                     {
                       Reference = new OpenApiReference
                       {
                         Type = ReferenceType.SecurityScheme,
                         Id = "Bearer"
                       }
                      },
                      new string[] { }
                    }
                });
});
builder.Services.AddDbContext<ApplicationBdContexte>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"))
);
builder.Services.AddIdentity<ApplicationUser, IdentityRole>()
    .AddDefaultTokenProviders()
    .AddEntityFrameworkStores<ApplicationBdContexte>()
    .AddErrorDescriber<MultilanguageIdentityErrorMessage>();

var apiSettingSection = builder.Configuration.GetSection("APISettings");
builder.Services.Configure<APISettings>(apiSettingSection);

var apiSettings = apiSettingSection.Get<APISettings>();
var cle = Encoding.ASCII.GetBytes(apiSettings.SecretKey);

builder.Services.AddAuthentication(opt =>
{
    opt.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    opt.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    opt.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(x =>
{
    x.RequireHttpsMetadata = false;
    x.SaveToken = true;
    x.TokenValidationParameters = new()
    {
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = new SymmetricSecurityKey(cle),
        ValidateAudience = true,
        ValidateIssuer = true,
        ValidAudience = apiSettings.ValidAudience,
        ValidIssuer = apiSettings.ValidIssuer,
        ClockSkew = TimeSpan.Zero
    };
});

builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
// Repositories
builder.Services.AddScoped<IDepartementRepository, DepartementRepository>();
builder.Services.AddScoped<IEpicerieRepository, EpicerieRepository>();
builder.Services.AddScoped<IEpicerieDetailsRepository, EpicerieDetailsRepository>();
builder.Services.AddScoped<IGabaritRepository, GabaritRepository>();
builder.Services.AddScoped<IGabaritDetailsRepository, GabaritsDetailsRepository>();
builder.Services.AddScoped<IItemRepository, ItemRepository>();
builder.Services.AddScoped<IUniteMesureRepository, UniteMesureRepository>();
builder.Services.AddScoped<IEpicerieDetailsRepository, EpicerieDetailsRepository>();
builder.Services.AddScoped<IInviteGabaritRepository, InviteGabaritRepository>();
builder.Services.AddScoped<IInviteEpicerieRepository, InviteEpicerieRepository>();
// Validateurs
builder.Services.AddScoped<IDepartementValidateur, DepartementValidateur>();
builder.Services.AddScoped<IGabaritValidateur, GabaritValidateur>();
builder.Services.AddScoped<IItemValidateur, ItemValidateur>();
builder.Services.AddScoped<IUniteMesureValidateur, UniteMesureValidateur>();
builder.Services.AddScoped<IEpicerieValidateur, EpicerieValidateur>();
builder.Services.AddScoped<IEpicerieDetailsValidateur, EpicerieDetailsValidateur>();
builder.Services.AddScoped<IGabaritDetailsValidateur, GabaritDetailsValidateur>();
builder.Services.AddScoped<IInviteGabaritValidateur, InviteGabaritValidateur>();
builder.Services.AddScoped<IInviteEpicerieValidateur, InviteEpicerieValidateur>();

builder.Services.AddRateLimitService(builder.Configuration.GetSection("RateLimitOption"));

builder.Services.AddCors(o => o.AddPolicy("Epicerie", builder =>
{
    builder
        .AllowAnyOrigin()
        .AllowAnyMethod()
        .AllowAnyHeader();
}));

var app = builder.Build();

// Configure the HTTP request pipeline.
//if (app.Environment.IsDevelopment())
//{
//    app.UseSwagger();
//    app.UseSwaggerUI();
//}
app.UseSwagger();
app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "Epicerie App v1");
    c.RoutePrefix = String.Empty;
});
app.UseHttpsRedirection();
app.UseCors("Epicerie");
app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();

app.Run();

When I try loccaly with this code uncommented and with the BD in Azure, it works:

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

So it is really the API that fails.

I do not know what to do, because the swagger appears, but when I try to connect, it makes 500. So maybe there's something to do with Azure but I'm not sure what!

Do you know how to solve this issue?

Upvotes: 0

Views: 468

Answers (1)

SiddheshDesai
SiddheshDesai

Reputation: 8167

After your Web API deployment with Swagger, Make sure you add the below settings in your Azure Web App Configuration or Environment Variable depending on your ui:-

ASPNETCORE_ENVIRONMENT:Development

enter image description here

enter image description here

And I have updated my Program.cs like below:- Reference - SO thread answer by Harshitha

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

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
    app.UseSwaggerUI(options =>
    {
        options.SwaggerEndpoint("/swagger/v1/swagger.json", "v1");
        options.RoutePrefix = string.Empty;
    });

}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

My Azure DevOps YAML pipeline:-

trigger:
  branches:
    include:
      - main

jobs:
- job: Build
  displayName: 'Build and Publish'
  pool:
    vmImage: 'ubuntu-latest'
  steps:
  - task: UseDotNet@2
    displayName: 'Install .NET Core SDK'
    inputs:
      version: '6.x'

  - task: DotNetCoreCLI@2
    displayName: 'Restore Dependencies'
    inputs:
      command: 'restore'
      projects: '**/*.csproj'

  - task: DotNetCoreCLI@2
    displayName: 'Build Project'
    inputs:
      command: 'build'
      projects: '**/*.csproj'
      arguments: '--configuration Release'

  - task: DotNetCoreCLI@2
    displayName: 'Publish Project'
    inputs:
      command: 'publish'
      projects: '**/*.csproj'
      publishWebProjects: true
      arguments: '--configuration Release --output $(Build.ArtifactStagingDirectory)'
      zipAfterPublish: true

  - task: PublishPipelineArtifact@1
    displayName: 'Publish Artifact'
    inputs:
      targetPath: '$(Build.ArtifactStagingDirectory)'
      artifactName: 'publishedApp'
      publishLocation: 'pipeline'

- job: Deploy
  displayName: 'Deploy to Azure Web App'
  dependsOn: Build
  pool:
    vmImage: 'ubuntu-latest'
  steps:
  - download: current
    artifact: 'publishedApp'

  - task: UseDotNet@2
    displayName: 'Install .NET Core SDK'
    inputs:
      version: '6.x'

  - task: AzureWebApp@1
    displayName: 'Azure Web App Deploy'
    inputs:
      azureSubscription: 'SID subscription (0151c365-f598-44d6-b4fd-e2b6e97cb2a7)'
      appType: 'webApp'
      appName: 'siliconwebappi'
      package: '$(Agent.BuildDirectory)/**/*.zip'
      deploymentMethod: 'auto'

Output:-

enter image description here

enter image description here

Upvotes: 0

Related Questions