0

ASP.Net MVC's routing magic still puzzles me occasionally, especially when it comes to error handling and redirection.

Why does http://foobar.com/Home/Index work but http://foobar.com/Home/Index.aspx generate a 404?

This matters to me because I want to do the occasional redirect:

protected void Application_BeginRequest(object sender, EventArgs e) {
    if (some condition) {
        HttpContext.Current.RewritePath("Home/Index.aspx");
    }
}

As it stands, this snippet doesn't work. If I leave the .aspx suffix in I get a 404, if I remove it, I get a cascade of calls to Application_BeginRequest.

Thanks as always, Duffy

duffy
  • 615
  • 1
  • 9
  • 25

1 Answers1

0

ASP.NET MVC maps URLs according to url-pattern rules defined in its routing. Only if a routing rule doesn't exist to match a given URL, MVC will assume that the requested url is for a physical file (and only if that feature is enabled also).

That said, unless you have a routing pattern (or a route, if you will) that matches "home/index.aspx", then there is no handler defined to work with that URL, and the MVC will fall back into assuming that a physical file is requested. Since there is no physical file at that path, it returns 404 - really, that file doesn't exist: I know that you do have it, but it's at a different location (/views/home/index.aspx).

However, even if you do request a correct path (e.g. "/views/home/index.aspx"), you'll still get a 404, because there is a web.config file in "views" folder with a rule that forbids accessing all files that way (they can only be accessed from within controllers, basically).

So, if you need to transfer the request to another controller/action, then there are a couple of ways to do that. See if these threads will help you:

How to simulate Server.Transfer in ASP.NET MVC?

How do I use Server.Transfer method in asp.net MVC?

Oh, and if "some_condition" is purely URL path matching, then you should probably do that at routing level.

Community
  • 1
  • 1
  • Does that mean something like this would not work? ( That's what I had in mind with the snippet in the first place) http://www.codeproject.com/Tips/219637/Put-the-website-in-Maintanance-Mode-Under-Construc – duffy Feb 02 '12 at 19:44
  • One more comment: Server.Transfer doesn't work for me because the way IIS is set up (no integrated pipeline, apparently.) – duffy Feb 02 '12 at 19:45