6

I'm trying to route a .aspx (webforms page) in my asp.net mvc project. I register the page in global.asax:

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapPageRoute("Tickets", "Reports/Tickets", "~/WebForms/Reports/Tickets.aspx");
routes.MapRoute("Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional });

The problem is, after i add the second line, the site stops to enter in my Home Controller (Index Action) and is redirecting to: http://localhost:37538/Reports/Tickets?action=Index&controller=Login%22 always that i run the project.

Project Details:

  • Asp.Net MVC 3
  • Forms Authentication
  • .Net 4.0

Obs: to reproduce this error, create a new asp.net mvc project as internet app, after create the Tickets webforms page inside a /WebForms/Reports folder, and register the new route. Run the project (probably you're logged), so now logoff and you will be redirected to http://localhost:35874/Reports/Tickets?action=LogOff&controller=Account, so why?

Vinicius Ottoni
  • 4,631
  • 9
  • 42
  • 64

1 Answers1

12

Solved! So, we need to add a route contraint to the webforms route to ensure that it only catches on incoming routes, not outgoing route generation.

Add the following class to your project (either in a new file or the bottom of global.asax.cs):

public class MyCustomConstraint : IRouteConstraint{
    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection){
        return routeDirection == RouteDirection.IncomingRequest;
    }
}

Then change the Tickets route to the following:

routes.MapPageRoute(
    "Tickets",
    "Reports/Tickets",
    "~/WebForms/Reports/Tickets.aspx",
    true, null, 
    new RouteValueDictionary { { "outgoing", new MyCustomConstraint() } }
);
Vinicius Ottoni
  • 4,631
  • 9
  • 42
  • 64
  • Thank you! This solved my issues where I couldn't log in to my pages anymore after adding a MapPageRoute. The submit-button on Login-page actually posted the values to the first page route. Do you have any source which describes this behavior and the reasoning behind it? – Mikael Koskinen Aug 24 '12 at 08:55
  • 1
    Here some links that help me to reach the solution: http://dotnet.dzone.com/news/custom-route-constraint-aspnet, http://blogs.imeta.co.uk/MBest/archive/2010/01/06.aspx and http://www.eworldui.net/blog/post/2008/04/ASPNET-MVC---Legacy-Url-Routing.aspx – Vinicius Ottoni Aug 24 '12 at 11:37
  • But specifically about you want, i don't have. – Vinicius Ottoni Aug 24 '12 at 11:44
  • +1 for including your sources @ViniciusOttoni. This helped me out when I was about to just lose patience. My issue was with calling MapPageRoute and MapRoute in the same solution on different projects; I was trying to use a mix of MVC and web forms. Hopefully this helps others in the same predicament. – Ant Aug 12 '16 at 09:42