Dynamic URL Rewriting on ASP.NET MVC

ASP.NET MVC has URL mapping to add custom routes so any URL can be processed by a controller.

For example,

routes.MapRoute(
"routename",
"products/{id}/{name}/", // URL
new { controller = "MyController", action = "MyAction"}
);

Here URL can be any URL with any dynamic parameters.

 

Redirect URL to existing file

If we need to redirect an URL “some_folder/{filename}” to a file in another folder “another_folder/{filename}”, we can do it using standard method MapPageRoute in the Global.asax file:

routes.MapPageRoute(“routename”, “some_folder/filename.jpg”, “~/another_folder/new_filename.jpg”);

 

But what if we need to do it for every file in the folder ?

For example, we need every file “some_folder/*.jpg” to be redirected to files in another folder “another_folder/*.jpg”.

It will be great to define a route with a dynamic filename:

routes.MapPageRoute(
"routename",
"some_folder/{filename}.jpg",
"~/another_folder/{filename}.jpg"
);

But it doesn’t work.

We can solve this problem using a controller action that will return file contents.

First, we add the route:

 

routes.MapRoute(
 
"routename",
"some_folder/{filename}.jpg",
new { controller = "Home", action = "RedirectImageFile"}
);

 

 

And add the following code to the action method in HomeController:

 

public class HomeController : Controller
{
 
public ActionResult RedirectImageFile(string filename)
{
string url = Url.Content("~/another_folder/"+filename+".jpg");
return base.File(url, "image/jpeg");
//return base.File(url, "application/octet-stream");
}
 
}

 

Now every time we access files “some_folder/prod1.jpg” or “some_folder/prod456.jpg” or any other file in that folder it will return the contents of files in another folder.

 

 

6 thoughts on “Dynamic URL Rewriting on ASP.NET MVC”

  • I have a problem, when I do this I get a “resource cannot be found” error, because for some reason URLs ending with a file extension don’t pass through the Routing system at all, instead it looks for the file and fails to find it and so it shows that error.
    I’m sure I’m missing a small thing but I can’t find it.

    Note: I’m using ASP.NET MVC 3

    Edit: I fixed it, apparently the {filename} route needs to be the first route otherwise it wont work even though no other route matches, I can’t understand why this is happening.

    • Anonymous says:

      The more generic route should come the last.

      What routes do you have? It should be a conflict with other routes.

      for example, you might have this route:
      routes.MapRoute(
      “Catch All”,
      “{*path}”,
      new { controller = “Error”, action = “NotFound” }
      );

      Another reason could be that your IIS doesn’t process files of specific type.
      But you said that it works when you place the route first, so it is not IIS.

      • The only other route I have is the one in the default MVC app, the “{controller}/{action}/{id}” one.
        and there is an area route for SecurityGuard which I got from nuget.

  • void Application_AcquireRequestState(object sender, EventArgs e)
    {
    if (System.Web.HttpContext.Current.Session != null && System.Web.HttpContext.Current.Session[“Test1”] != null)
    {

    string V = System.Web.HttpContext.Current.Session[“Test1”].ToString();
    RouteTable.Routes.MapPageRoute(“”, “WebForm001”, V);

    }
    }
    System.Web.HttpContext.Current.Session[“Test1”].ToString(); not change

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>