I am building an ASP.NET 8 Web API. I got the following error in Postman when I ran it the first time:
GET https://localhost:5001/home
Error: connect ECONNREFUSED 127.0.0.1:5001
Request Headers
User-Agent: PostmanRuntime/7.39.0
Accept: */*
Cache-Control: no-cache
Postman-Token: 173f13c0-5d2f-4fe0-9d75-df150fcc3fbf
Host: localhost:5001
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
From the following API method:
namespace API.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class HomeController : ControllerBase
{
public string Index()
{
return "Hello API!";
}
}
}
Very simple. The error baffled me. I checked all the usual culprits, HTTPS, proxy etc. nothing.
I noticed that the WeatherForecast example Controller and code were missing from the project I just created. So, I decided to take a look at Program.cs to see what was there. This is what I found:
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
// 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.UseHttpsRedirection();
var summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
app.MapGet("/weatherforecast", () =>
{
var forecast = Enumerable.Range(1, 5).Select(index =>
new WeatherForecast
(
DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
Random.Shared.Next(-20, 55),
summaries[Random.Shared.Next(summaries.Length)]
))
.ToArray();
return forecast;
})
.WithName("GetWeatherForecast")
.WithOpenApi();
app.Run();
record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary)
{
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}
Strange code to put in Program.cs It must be something new in .NET 8. So I deleted all the unwanted code and got this:
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
// 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.UseHttpsRedirection();
app.Run();
Now my simple little controller works! I hope this helps someone who encounters the same issue.