Home > other >  How to return a file if url does not match any endpoints Asp.Net Core
How to return a file if url does not match any endpoints Asp.Net Core

Time:08-03

In my request pipeline, I check whether the url is pointing towards a static file in a certain directory, then I check if it maps to a controller method.

var pathToDirectory = "some path";
app.UseFileServer(new FileServerOptions()
{
    FileProvider = new PhysicalFileProvider(pathToDirectory),
    RequestPath = "",
});

app.UseAuthorization();
app.MapControllers();

I would like to add another piece of middleware that says "If the url did not react any static files or controller methods, return myFile". How do I do this?

CodePudding user response:

If you want to return file if there is no route map the request, I suggest you could use asp.net core middleware to achieve it.

You could put the codes inside the startup.cs or program.cs like below:

        app.Use(async (ctx, next) =>
        {
            await next();

            if (ctx.Response.StatusCode == 404 && !ctx.Response.HasStarted)
            {

                //Re-execute the request so the user gets the error page
                string originalPath = ctx.Request.Path.Value;
                ctx.Items["originalPath"] = originalPath;
                ctx.Request.Path = "/home/PageNotFound";
                await next();
            }
        });

And generate a action method to return the file like below:

    public IActionResult PageNotFound()
    {

   
        var myfile = System.IO.File.ReadAllBytes("wwwroot/Files/FileContentResult.pdf");

        return new FileContentResult(myfile, "application/pdf");
    }

Please notice this middleware show put before the routing middleware, more details ,you could refer to below codes:

        app.Use(async (ctx, next) =>
        {
            await next();

            if (ctx.Response.StatusCode == 404 && !ctx.Response.HasStarted)
            {

                //Re-execute the request so the user gets the error page
                string originalPath = ctx.Request.Path.Value;
                ctx.Items["originalPath"] = originalPath;
                ctx.Request.Path = "/home/PageNotFound";
                await next();
            }
        });

        app.UseHttpsRedirection();
        app.UseStaticFiles();
  • Related