Wednesday, November 21, 2012

Advanced Routing In Asp.Net MVC4



You can always use a catch all syntax ( I have no idea if the name is proper).
Route:
routeTable.MapRoute( "Path", "{*path}", new { controller = "Pages", action = "Path" });
Controller action is defined as:
public ActionResult Path(string path)
In the action for controller you will have a path, so just have to spilt it and analyse.
To call another controller you can use a RedirectToAction ( I think this is more proper way). With redirection you can set up a permanent redirectionfor it. Or use a something like that:
internal class MVCTransferResult : RedirectResult { public MVCTransferResult(string url) : base(url) { } public MVCTransferResult(object routeValues) : base(GetRouteURL(routeValues)) { }
    private static string GetRouteURL(object routeValues)
    {
        UrlHelper url = new UrlHelper(
            new RequestContext(
                    new HttpContextWrapper(HttpContext.Current),
                    new RouteData()),
                    RouteTable.Routes);
        return url.RouteUrl(routeValues);
    }

    public override void ExecuteResult(ControllerContext context)
    {
        var httpContext = HttpContext.Current;

        // ASP.NET MVC 3.0
        if (context.Controller.TempData != null &&
            context.Controller.TempData.Count() > 0)
        {
            throw new ApplicationException(
                 "TempData won't work with Server.TransferRequest!");
        }
        // change to false to pass query string parameters
        // if you have already processed them
        httpContext.Server.TransferRequest(Url, true);

        // ASP.NET MVC 2.0
        //httpContext.RewritePath(Url, false);
        //IHttpHandler httpHandler = new MvcHttpHandler();
        //httpHandler.ProcessRequest(HttpContext.Current);
    }
}

No comments:

Post a Comment