Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if a route (ASP.NET MVC) exists for a given path? [duplicate]

I have a list of local URL’s and I need to determine if they are “valid MVC paths”. How can I check if a URL (path) maps to a MVC controller?

Phil Haack's Route Debugger will find a route that match the current request and does so using the current HttpContext. I would like to get this info without building up a mock HttpContext - if possible.

like image 307
mawtex Avatar asked Feb 03 '11 03:02

mawtex


People also ask

Can we have multiple routes in MVC?

Multiple Routes You need to provide at least two parameters in MapRoute, route name, and URL pattern. The Defaults parameter is optional. You can register multiple custom routes with different names.

How many routes are there in MVC?

ASP.NET MVC offers two approaches to routing: The route table, which is a collection of routes that can be used to match incoming requests to controller actions.

How can we detect that an MVC controller is called by post or get?

You can check the Request. HttpMethod property.


1 Answers

You can call RouteTable.Routes.GetRouteData with a mocked HttpContextBase.

The routes are matched internally using the request's AppRelativeCurrentExecutionFilePath.
However, this functionality is not exposed, so you need to pass an HttpContextBase.

You need to create an HttpContextBase class which returns an HttpRequestBase instance in its request property.
The HttpRequestBase class needs to return your path, beginning with ~/, in its AppRelativeCurrentExecutionFilePath property.

You don't need to implement any other properties, unless they're used by IRouteConstraints.

To check whether you got an MVC route, check whether the resulting routeData.Handler is MvcRouteHandler.

like image 70
SLaks Avatar answered Sep 29 '22 00:09

SLaks