I don't want to use UsePathBase() for some reasons. I try to use MapExtensions.Map() like below. But it does not work. Respond with "404 Not Found" when I request "/api/v1/WeatherForecast".By the way, this endpoint url is "/WeatherForecast", but respond with "404 Not Found" either.
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
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 configuration = builder.Configuration.
AddEnvironmentVariables()
.SetBasePath(System.IO.Directory.GetCurrentDirectory())
.Build();
var app = builder.Build();
app.UseDefaultFiles();
app.UseStaticFiles();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.Map("/api/v1", apiApp =>
{
apiApp.UseRouting();
apiApp.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
});
app.MapFallbackToFile("/index.html");
app.Run();
I want to set the root path by app.Map().
You can use the PathBase
(via the UsePathBase
call):
app.UsePathBase("/api");
app.UseRouting();
app.UseAuthorization();
app.MapControllers();
note that this will make both your controller available via both api/controller
and controller
routes.
As for your approach - for .NET 8 adding explicit call to app.UseRouting()
makes the controllers available (for .NET 9 seems to be working fine without it):
app.Map("/api", apiApp =>
{
apiApp.UseRouting();
apiApp.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
});
app.UseRouting();