Search code examples
c#asp.net-coreswagger.net-7.0minimal-apis

ASP.NET Core 7 Minimal API - Swagger doesn't start


We have a minimal API application, and whenever we start the app, we get a "Localhost not found" error instead of getting the Swagger interface. If we add the /swagger to the end of the URL, Swagger comes up fine. Are we missing something when trying to get it to default to the Swagger interface?

Our program.cs looks like this:

using Dapr.Client;
using ErpInterfaceService.Abstractions;
using ErpInterfaceService.Data;
using ErpInterfaceService.Models;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddEndpointDefinitions(typeof(Message));
builder.Services.AddHealthChecks();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

// TODO: Move this connection string to a secrets store. 
builder.Services.AddDbContext<ErpInterfaceContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("ErpInterface")));

builder.Services.AddSingleton(new DaprClientBuilder().Build());

var app = builder.Build();

// Apply any new migrations to the database
using (var scope = app.Services.CreateScope())
{
    var dbContext = scope.ServiceProvider.GetRequiredService<ErpInterfaceContext>();
    dbContext.Database.Migrate();
}

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseEndpointDefinitions();
app.MapHealthChecks("/health");

app.Run();

Solution

  • Are we missing something when trying to get it to default to the Swagger interface?

    No, by default:

    The Swagger UI can be found at https://localhost:<port>/swagger.

    It seems that your app does not have the root url handler, i.e. something like:

    app.MapGet("/", () => "ok");
    

    The opening browser opening action/url opened in the development environment is usually controlled by launchSettings.json file. Open it (usually is placed in Properties folder), locate the launched profile and add/change launchUrl property:

    {
      // ... 
      "profiles": {
        "http": {
          "commandName": "Project",
          "dotnetRunMessages": true,
          "launchBrowser": true,
          "launchUrl": "swagger", // <---- here
          "applicationUrl": "http://localhost:5166",
          "environmentVariables": {
            "ASPNETCORE_ENVIRONMENT": "Development"
          }
        },
        // ...
      }
    }
    

    Another option is to change the swagger url to the root one - check out this this answer.