Mike
Mike

Reputation: 123

Redirect requests for static files in a local directory to MVC Action

The problem is a local directory containing sub-directories each with multiple zip files. We cannot change the links external to the system but must now reroute them to S3. The application is built on ASP.NET MVC 5.

Proposed Solution (what I am trying): To capture all inbound requests for /directory/subdirectory/xyz.zip and redirect them to an MVC controller action to send them the proper file from S3.

Structure:

root/DIRECTORY/*subdirectories/*.zip 

Example urls:

www.somewhere.com/Packages/{Guid}/{Guid}-IDENTIFIER.zip
  1. added new controller Packages

  2. added the following route

routes.MapRoute(
               "RedirectDownloads",
                "{controller}/{key}/{zip}",
                new { controller = "Packages", action = "Index"},
                new
                {
                    key = @"[{|\(]?[0-9a-fA-F]{8}[-]?([0-9a-fA-F]{4}[-]?){3}[0-9a-fA-F]{12}[\)|}]?",
                    zip = @"[a-fA-F0-9]{8}(?:-[a-fA-F0-9]{4}){3}-[a-fA-F0-9]{12}\-.*\.zip"
                }
                );

This obviously isn't hit due to these being static files on the file system so I also tried the following under ..

<add name="Zips-ISAPI-Integrated-4.0" path="*.zip" verb="GET" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />

But this causing IIS to throw an error.

Upvotes: 1

Views: 1312

Answers (1)

Rob
Rob

Reputation: 27367

In your web.config, find the <handlers/ > tag

Add this:

<add name="zipThingy" path="*.zip" verb="GET" type="MikesProject.ZipThingy"/>  

Then add this class:

namespace MikesProject
{
    public class ZipThingy: IHttpHandler, IReadOnlySessionState
    {
        public void ProcessRequest(HttpContext context)
        {
            var request = context.Request;
            var response = context.Response;
        }
    }
}

Then either:
1. Return a straight redirect to the S3 URL, like this: response.RedirectPermanent("http://S3.URL.ZIP");
2. You put your logic into ProcessRequest instead of your controller, which will download the zip from S3 and return the file, or
2. Have response return a redirect to your controller, passing the relevant data. You can get the filename like this: Path.GetFileName(context.Request.PhysicalPath)

Upvotes: 2

Related Questions