Url Pattern from RouteTable in MVC? - model-view-controller

I have my route collection and want to retrieve the url pattern (defined in global.asax) of a given route.
In application:
var route = RouteTable.Routes["UserIndex"];
Global.asax:
routes.MapRoute(
name: "UserIndex",
url: "u/{userId}"
In the web application I am not able to access the Url Pattern (in the route object) which were defined in global.asax. Is there another way?
Im asking this because I need to define some route patterns to be used with Knockout.js in template list.

Try something like:
Route userRoute = RouteTable.Routes[UserIndex"] as Route;
string pattern = userRoute.Url;

Related

From route configuration to attribute routing

I have the following route configured in my ASP.NET Web API 2 Project:
config.Routes.MapHttpRoute(
name: "1MandatoryStringParameter",
routeTemplate: "api/{controller}/{data}",
defaults: null,
constraints: new { data = #".+?" }
It is used with the following controller method (notice the ArrayInput attribute):
[ArrayInput("data",Separator = ',')]
public async Task<IHttpActionResult> Get(int[] data)
{
...
}
I would like to use Attribute routing instead.
I tried to replace the call to MapHttpRoute with the following attributes:
[HttpGet]
[Route("api/ActionsForItemTypesList/{data:regex(.+?)}", Name = "1MandatoryStringParameter")]
Out of the box it does not work. I can't reach my method with an URL like:
api/ActionsForItemTypesList/1,2
If get a 404 Method not found.
This is working fine with route configuration.
Any help appreciated.
EDIT : fixed the client URL.
EDIT 2 : This is an ApiExplorer Issue (Swashbuckle leverage ApiExplorer)
If I modify the Route attribute and remove the parameter (ie. {data}) the ApiDescription becomes available.
Make sure you have enabled attribute routing:
config.MapHttpAttributeRoutes();
Also in your Route attribute you have specified that the data parameter must be part of the path and not a query string. So make sure that you are calling the action correctly from the client:
api/ActionsForItemTypesList/1,2
Also notice that the prefix that you indicated in your Route attribute is api/ActionsForItemTypesList and not api/Controller like you were trying to invoke it.

web api support parameters while they don't have one

http://localhost:xxxx/api/BindAppointmentResources
works fine for me but when I'm trying to add any invalid object after controller (with this ? "http://localhost:xxxxx/api/BindAppointmentResources?Userid") in URL its gets the same result
I tried action-based routing , attribute routing so far but same result?
PS : I don't have parameters in WEB API
Route Config :
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}
Query string parameters will automatically get bound to your parameters that have the same name in web api.
If no parameter names are found it will route the request to the base url (which is the url before the question mark).
So this url
http://localhost:xxxx/api/BindAppointmentResources?UserID=1
will, if no method with parameter name that match UserID are found, end up being routed to
http://localhost:xxxx/api/BindAppointmentResources
In the Get method you can still get the query string
var queryString = this.Request.GetQueryNameValuePairs();
To prevent binding parameters from query string and only allow bindings from route values, you could remove the default QueryStringValueProviderFactory from the default HttpConfiguration configuration. Read more about it in this article

difference between URL rewriting and URL routing mvc

I am trying to learn MVC and need help in understanding the difference between URL rewriting and URL routing in MVC.
URL Routing is the routing done by MVC which is , When we type something in the url space, then it will first invoke the
RouteConfig.RegisterRoutes(RouteTable.Routes);
which is in Global.asax.cs Application_Start() method if you put a break point in that then you could understand the routing method , then it will call the
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
Which is in App_start=>RouteConfig class you can find out the RegisterRoutes method here . Here we can define the structure of our url and here it will decide which controller and action should be invoked.
This process is url Routing
URL rewriting is entire diff concept
Let us assume our controller name is Customer and action name is Login
when we run the application our url will be like the below
http://Localhost:233/Customer/Login
but the client ended http://Localhost:233/Login only, for SEO purposes
In order to achieve this we have to rewrite the url by keeping the same controller and action name
to know more about url rewriting i have explained attribute rewriting in http://grandhah.blogspot.in/2015/07/url-rewriting-in-mvc-4-attribute-routing.html Please visit and let me know you are clarified enough.. good day

MVC 3 Custom Url Routing

I want to create a custom route, as a default mvc creates route like this:
domain.com/deals/detail/5
but in my case i want to create a custom route for it:
domain.com/delicious-food-in-paris
so it has to look for deals controller's detail action with passing an id value 5 to it.
how can i do it?
Thanks
This route maps all one segment urls to the detail method of the deals controller and passes one string argument called dealName to it:
routes.MapRoute(
null,
"{dealName}",
new { controller = "deals", action = "detail" }
);
But as AdamD have said, you should register that route as the last route in your setup because it will catch all urls which have only one segment.
With this approach you have to lookup your deal by name which might be not acceptable. So many apps use a hybrid approach and include the name and the id in the url like this:
domain.com/deals/5-HereComesTheLongName
Then you can use a route like this to get the id and optionally the name:
routes.MapRoute(
null,
"{id}-{dealName}",
new {
controller = "deals",
action = "detail",
dealName = UrlParameter.Optional
}
);
You can do this by defining a custom route in the Global.asax RegisterRoutes function. You would need to add this route after the default route so if the default controller action id pattern fails it will try to execute the final route.
An example would be to use the following:
routes.MapRoute(
"RouteName",
"/{uri}", //this is www.domain.com/{uri}
new { controller = "Controller", action = "ByUri" },
new { uri = #"[a-z\-0-9]+" } //parameter regex can be tailored here
);
After you register this route you can add a new custom controller to handle these routes, add the action that will handle this and accept a string as the parameter.
In this new action you can have a database lookup or some hardcoded valide routes that return Views.

Routes and Url helpers confusion

I'm a little confused on the MVC front for this reason, I have the following default route defined;
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
When I use a Url helper, i.e.
#Url.Action("MyAction")
it generates this url;
/?action=MyAction&controller=MyController
and never finds my action method. How are the Urls generated by the helpers and how do I correct this?
Just use the overload to specify the action and controller:
#Url.Action("MyAction", "MyController")
If you use the overload which only takes the action name, the controller is taken from the current route data. Default routing doesn't come into it.
i.e.
#Url.Action("MyAction")
is equivalent to
#Url.Action("MyAction", (string)ViewContext.RouteData.Values["controller"])
I had the same issue, I had a web app that was built used WebForms and slowly migrating parts to MVC, to support both I had a route entry which ended up breaking the routing evaluation code and caused the funny action urls
this blog post fixed my issue

Resources