Search code examples
asp.net-coremiddlewarestatic-files

Redirect to Static file asp.net core


I'm developing an application that contains Images under the wwwroot folder. When the image is called (something.com/Images/img.png) I need a code to run, after finishing I need the image to appear. Is it possible after the code is executed to redirect the pipe line to static file (image). my code looks like this:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
   app.Map("/images", images =>
   {
      images.Map("/img.png=", img =>
      {
         HandleImages(app);
      });
   });
}

private void HandleImages(IApplicationBuilder app)
{
   app.Run(async (context) =>
   {
      //do something
      //redirect to The Image 
   });
}

I tried using app.UseStaticFiles(); the image appeared but the code isn't executed.


Solution

  • Since the image URL is the same, you can't redirect to the same image -- it would be an infinitive redirect loop.

    You have two options:

    1. Use a different URL for an image, then you could return redirect response to the image.
    2. If you need to keep the image URL the same as the handler, then you can return an image stream response with image/jpeg etc. mime header. No redirect needed.

    Let me know if any of the options above worked for you.

    Update.

    Here is an example of #1 - redirect to an image with a different URL using pipeline.

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        // Make sure static files serving enabled
        app.UseStaticFiles();
    
        app.Map("/images", images =>
        {
            images.Map("/img.png", img =>
            {
                HandleImages(img);
            });
        });
    }
    
    private void HandleImages(IApplicationBuilder appBuilder)
    {
        appBuilder.Run((context) =>
        {
            //do something
            // ..
            //redirect to The Image 
            context.Response.Redirect("/images/another.jpg");
            return Task.FromResult(0);
        });
    }
    

    Summary:

    • Enable app.UseStaticFiles();.
    • Pass img into HandleImages() method.
    • Return redirect response with a path to the actual image. The image URL must be different from the mapped handler URL.