I have an asp.net core 6.0 app with:
WeatherForecastController
index.html
inwwwroot
folder.
I have configured index.html
as file fallback. This is themain
method of program.cs
;
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
var app = builder.Build();
// Configure the HTTP request pipeline.
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.UseStaticFiles();
app.MapFallbackToFile("index.html");
app.Run();
}
I wanted to return 404 when the path
starts with /api
and there is no matching controller action.
I tried adding a middleware after app.MapControllers
but the middleware executes before the controller gets called and the app always returns 404 when trying to call the API.
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
var app = builder.Build();
// Configure the HTTP request pipeline.
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.UseApiNotFound();
app.UseStaticFiles();
app.MapFallbackToFile("index.html");
app.Run();
}
This is the middleware:
public class ApiNotFoundMiddleware
{
private readonly RequestDelegate next;
public ApiNotFoundMiddleware(RequestDelegate next)
{
this.next = next;
}
private static PathString prefix = "/api";
public Task InvokeAsync(HttpContext context)
{
if (context.Request.Path.StartsWithSegments(prefix))
{
context.Response.StatusCode = (int)HttpStatusCode.NotFound;
return Task.CompletedTask;
}
else
{
return this.next(context);
}
}
}
So
How to return 404 if path starts with '/api', there is no matching controller action and there is a file mapped as fallback?
or
is there a way to restrict fallback file to paths that do not start with /api
CodePudding user response:
You can use a different IApplicationBuilder for different conditions in your Progam.cs or Startup.cs:
e.g.:
app.MapWhen(ctx => !ctx.Request.Path.StartsWithSegments("/api"), appBuilder =>
{
appBuilder.UseRouting();
appBuilder.UseEndpoints(ep =>
{
ep.MapFallbackToFile("index.html");
});
});
CodePudding user response:
if you add app.UseMiddleware<ApiNotFoundMiddleware>();
here like so :
app.UseHttpsRedirection();
app.UseMiddleware<ApiNotFoundMiddleware>();
app.UseAuthorization();
This returns 404 if you try navigate to anything with /api
Would this be what you're trying to achieve?