CodexBloom - Programming Q&A Platform

Why is my HttpClient returning 404 when trying to access a Swagger UI on ASP.NET Core 6?

👀 Views: 88 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-08
asp.net-core swagger httpclient api C#

I'm collaborating on a project where I tried several approaches but none seem to work... I'm working on an ASP.NET Core 6 application, and I have set up Swagger for API documentation. However, when I try to access the Swagger UI using `HttpClient`, I consistently receive a 404 Not Found response. I've ensured that the Swagger middleware is correctly configured in `Startup.cs` like this: ```csharp public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" }); }); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); c.RoutePrefix = string.Empty; // Set Swagger UI at the app's root }); } ``` I can access the JSON endpoint at `/swagger/v1/swagger.json` without issues, so it seems like the API is registered correctly. However, when I use `HttpClient` to request the Swagger UI page, like this: ```csharp using (var client = new HttpClient()) { var response = await client.GetAsync("http://localhost:5000/"); var content = await response.Content.ReadAsStringAsync(); Console.WriteLine(content); } ``` I receive a `404 Not Found` behavior. I've tried various combinations of URLs including appending `/swagger` or `/swagger/index.html`, but they all return the same behavior. I've also verified that my application is running and accessible. What could be causing this scenario? Is there a specific configuration I might be missing, or could it be related to the environment setup? Any insights would be appreciated! My development environment is macOS. I'm on Ubuntu 22.04 using the latest version of C#.