Thursday, April 14, 2011

Combining ASP.NET WebForms and ASP.NET MVC

I created a page route to integrate my MVC application with a WebForms page that exist in my project:

public static void RegisterRoutes(RouteCollection routes)
{    
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");    
// register the report route    
routes.MapPageRoute("Reports","Reports","~/Pages/ReportViewer.aspx");    
routes.MapRoute("Default","{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional });
}

This works when browsing to the specific url’s. However, I noticed this route created a problem whenever I use an  Html.ActionLink in my Views:


<%: Html.ActionLink("Home", "Index", "Home") %>

When I load the page in the browser the link appears like:

http://localhost:12345/reports/test?action=Index&controller=Home

Unfortunately I can't place the route at the bottom, since the webform route has more specific parameters than the MVC route. I was able to solve this problem by introducing a new constraint.

I created a new constraint called IncomingRequestConstraint. This constraint  simply return false for outgoing Urls(so that all Html helpers will work as expected).

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

In the global.asax, I added this constraint to the WebForms route:

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");    
// register the report routes    
routes.MapPageRoute("Reports","Reports","~/Pages/ReportViewer.aspx", false, null, new RouteValueDictionary(new { controller = new IncomingRequestConstraint() }));    

3 comments:

Anonymous said...

Thanks. Its the solution I was looking for. I would like to know why this works!

Anonymous said...

Thank you Bart, this solution has resolved the difficulty with outgoing routes and webforms. Thank you for documentating it so clearly.

Anonymous said...

nice job. Thank you.