Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to set the root path of the url for my api endpoints?

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().

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading