Search code examples
asp.net-core-mvcasp.net-mvc-routing

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


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


Solution

  • 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