ASP.NET Core MVC redirect all subdirectory and files in specific folder with route in controller

35 Views Asked by At

I'm working on an ASP.NET Core 8 MVC project, and I need to set up a redirect routing for all files and subfolder into a specific folder.

This work great for urls like /images/foo.png but not for /images/sub1/foo.png nor for /images/sub1/sub2/foo.png.

[Route("/images/{restOfPath}")]

I need a route to capture everything in the images folder.

Thank you all

1

There are 1 best solutions below

0
Fengzhi Zhou On BEST ANSWER

You can use a "catch-all" parameter ** to implement this. Here is a sample.

private readonly IWebHostEnvironment _env;

public SampleController(IWebHostEnvironment env)
{
    _env = env;
}

[HttpGet("/Images/{**restOfPath}")]
public IActionResult Index(string restOfPath)
{
    var imagesRoot = Path.Combine(_env.ContentRootPath, "images", restOfPath);
    var contentType = "image/png";

    return PhysicalFile(imagesRoot, contentType);
}

enter image description here enter image description here