3

I've created a very basic .net CORE WEB API, following a youtube guide. Everything works fine when I debug from visual studio. it opens my browser and directs me to the swagger ui site.

But when I run outside visual studio, starting the exe from the build/bin folder I can't get to that swagger site. in a command propt the exe file says it is listening on http on port 5000. so while this is running go to this url http://localhost:5000/swagger/index.html

anyone have a hit on what I'm missing here ?

appsettings.json

{
  "ConnectionStrings": {
    "DefaultConnection": "server=myServerXXXX;database=myDataBaseXXXX;User ID=mydbUserXXXXX;Password=myPasswordXXX"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*"
}

program.cs

global using ShoppingList.API.Data;
global using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
builder.Services.AddDbContext<ShoppingItemDataContext>(options =>
{
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));
});

// 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.UseAuthorization();

app.MapControllers();

app.Run();

Simon Bruun
  • 59
  • 1
  • 5

1 Answers1

2

By default dotnet runs applications with the production environment and you have swagger enabled for the dev environment only. change the condition or pass the "--environment production" argument (or configure host environment: e.g. https://enlabsoftware.com/development/dotnet-core-environment-how-config-examples.html)

Jaume
  • 744
  • 1
  • 7
  • 21
  • Thanks, that was the problem. the problem was the if (app.Environment.IsDevelopment() {...} when outside of visual studio it is production it seems, so the UseSwagger() and useSwaggerUI is not started. Thanks. – Simon Bruun Mar 31 '22 at 17:30