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.
Comments
-
Mohanjerry1
-
http://www.hassanselim.me/ Hassan Selim
-
Anonymous
-
http://www.hassanselim.me/ Hassan Selim



