Reputation: 8412
I'm trying to get the URL segments of a page request in the global.asax file using HttpContext.Current.Request.RawUrl
. My code is as follows:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // Parameter defaults
new { controller = "Home|Account" }
);
var url = HttpContext.Current.Request.RawUrl;
var pageTitle = url.Split('/')[1];
routes.MapRoute(
"SendToCustomController",
"{*url}",
new { controller = "Custom", action = "Index", title = pageTitle }
);
}
The first time if I type in an address such as devserver:1234/test, I get the string 'test' sent through to the controller. The problem is, in subsequent requests that have a different segment such as devserver:1234/confused, I still get 'test' sent through to the controller.
The aim of this is for any request that doesn't have a designated controller, the controller segment of the URL is passed to a custom page controller which will see if there are any user generated pages in the DB with that title. If there is, the page will be loaded, if there's not the standard 404 will be thrown.
Any help to sort out the issue above, or a better way to achieve this will be great!
Upvotes: 0
Views: 1364
Reputation: 1038720
Your route token is called {url}
in the registration and then you use some title = pageTitle
constraint which I don't know from where it comes (actually it's hardcoded in your RegisterRoutes static method which obviously is run only once for the entire lifetime of the application for the very first request that hits it). You should avoid accessing anything HttpContext
related in your Application_Start
methods. If you arunning in IIS7+ integrated pipeline mode, that's not even allowed.
So try the following:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new { controller = "Home|Account" }
);
routes.MapRoute(
"SendToCustomController",
"{*url}",
new { controller = "Custom", action = "Index" }
);
}
and then:
public class CustomController : Controller
{
public ActionResult Index(string url)
{
// TODO: do your checks here based upon the url parameter
// and return HttpNotFound(); in case it doesn't match anything
}
}
Upvotes: 1