I want to have a route that looks something like: www.abc.com/companyName/Controller/Action/Id
However, all the company names need to map to the same "base" controllers, regardles of what the name is. I only need the companyName for authentication purposes.
Also, if there's no companyName provided, I need to map to a different set of controllers altogether.
How do I do this? I'd also appreciate a good routing resource so I don't have to ask questions like this.
routes.MapRoute(
"CompanyRoute",
"{companyName}/{controller}/{action}/{id}",
new { controller = "MyBaseCompanyController", action = "Index", id = "" }
);
routes.MapRoute(
"NoCompanyRoute",
"{controller}/{action}/{id}",
new {controller = "DifferentDefaultController", action = "Index", id = "" });
Routing is quite a complex topic, but it's covered well in Professional ASP.Net MVC 1.0. For online resources, I would suggest starting here, and then coming back to Stack Overflow ;)
In case if you wish to Resolve the errors caused due to routing . i suggest the following tool , which i found to be extremely useful.
Route Debugger
Go to Global.asax.cs, and add the following route in the RegisterRoutes() method before the "Default" route:
routes.MapRoute(
"Vanity", // Route name
"{company}/{controller}/{action}/{id}", // URL with parameters
new { company = "", controller = "Home", action = "Index", id = "" } // Parameter defaults
);
Related
This question already has answers here:
Routing in ASP.NET MVC, showing username in URL
(2 answers)
Closed 6 years ago.
Introduction
I am working on demo application where users can register.Users table have "username" field.There is "detail" action in "home" controller accepting parameter of string "username".
Code
public ActionResult Detail (string username)
{
return View();
}
Then url will be
www.example.com/home/Detail?username=someparam
Problem
Can i setup route like that ?
www.example.com/someparam
If its possible, then please let me know. Any kind of help or reference will be appreciated.
Thanks for your time.
That is doable if you change the way your routes are defined. Let's assume that you use dot net 4.5.2
Have a look in RouteConfig under App_Start.
A typical route definition is defined like this :
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Nothing stops from changing the route to look like this :
routes.MapRoute(
name: "Default",
url: "{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
We are basically hardcoding the controller and action to be a certain value so now you could just have url/paramname and it will hit the hardcoded combination.
This being said I would not do things like this as it's against the way MVC works
MVC routes are url/controller/action. You can skip the action for generic stuff like an Index for example and your URL becomes url/controller. MVC needs to be able to identify which controller you want to hit and which action and it's best to stay within the conventions it has.
Plus, each application will typically have more than one controller, which allows a nice Separation of Concerns. Now you've hardcoded yourself ito having just one controller and action.
What you are suggesting can be done a lot easier in a webforms manner though so maybe you want to look into that.
If you define code like this
[HttpGet, Route("api/detail/{username:string}")]
public ActionResult Detail (string username)
{
return View();
}
Then url will be
www.example.com/api/Detail/someparam
So I guest you define as following, please try with your own risk!
[HttpGet, Route("/{username:string}")]
Url will be:
www.example.com/someparam
I have tried routes.mapRoute but i can't figure a way in MVC 3 to use it make a root path route to an action. e.g mywebsite.com/party should redirect to mywebsite.com/events/party where events is the controller and party is the action.
Is this even possible?
Without seeing your existing routes, its hard to give you an exact solution.
One rule to keep in mind:
MVC will resolve the first in your route collection that matches the requested URL
not necessarily the most specific match.
Make sure you do not have another rule that would also satisfy that route placed earlier in your code, e.g. the routing algorithm might be finding a "party" controller and "index" action because you have a default rule like:
routes.MapRoute(
"Default",
"{action}",
new { controller = "Home", action = "Index" }
);
placed before your rule.
You need to put something like
routes.MapRoute(
"PartyRoute",
"party",
new { controller = "Events", action = "Party" }
);
BEFORE any route that might match a URL with just a single parameter
routes.MapRoute(
"Default",
"{action}",
new { controller = "Events", action = "Index" }
);
Global.asax.cs has the following code on initialization:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
What I'm asking is, how does it know that what it gets for "{controller}" will be the name of the Controller class to be invoked? Are there tokens defined somewhere? if so, can I list them?
If I define additional tokens (like "{lang}") will it assume they are additional parameters?
(I'm developing a custom URL rewrite/redirect handler, and I need it to work with MVC...)
What is the most practical way to define custom patterns and "aliases" for URLs?
The Mvc runtime has the controller and action tokens hardcoded. In addition there is also "area" but thats about it.
#TDaver If I define additional tokens (like "{lang}") will it assume they are additional parameters?
yes. If you define, for instance, a parameter like lang, it wil detect it. Think about like that, it will be the querystring field called lang of the page. and you can create a route for a pretyy url. Like below;
routes.MapRoute(
"Default", // Route name
"{lang}/{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
so the url will be like ; http://example.com/en/home/about
Also, the most important part of routing is to understand that the routes will be picked by order. for instance, if you have multiple routes matching your current request, the first route will be picked by MVC Framework.
I reccomend you to have a look at phil haccked's RouteDebugger
Also you can create route constraints for advanced routing options as well.
I have this two routes.
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional });
routes.MapRoute(
"Paging", // Route name
"{controller}/{action}/p{currentPage}",
new { controller = "Home", action = "Index" },
new { currentPage = "\\d+" });
I have this Controller
public class MyController
{
public ActionResult All(int currentPage = 1)
{
// some code executed here
return View(pList);
}
}
Why this url goes to the first route /My/All/p5
Can someone point me to good tutorial about routes?
Routes need to be registered in the right order, as they are processed in the same order in which they are registered. Your first route is essentially a catch all, so it will also match /My/All/p5. Register that route first:
routes.MapRoute(
"Paging", // Route name
"{controller}/{action}/p{currentPage}",
new { controller = "Home", action = "Index" },
new { currentPage = "\\d+" });
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional });
Reading : Steven Sanderson has very good explanation of routing in his book ( Pro MVC 2 ) in chapter 8. (You can find it here)
From the book:
If there’s one golden rule of routing,
this is it: put more-specific route
entries before less-specific ones.
Yes, RouteCollection is an ordered
list, and the order in which you add
route entries is critical to the
routematching process.
I have a series of blog posts on Routing you can read here: http://haacked.com/tags/Routing/default.aspx
Also, the route debugger http://haacked.com/archive/2008/03/13/url-routing-debugger.aspx is a useful tool for playing around with routing and understanding why a route you think should match is not matching.
BTW, Matthew Abbot is correct. You need to re-order the routes. Nazar's quote from Steven Sanderson's book has the reason why that's the case. Routing evaluates routes in order and the first one wins.
Here's the simple exercise I would have done to debug this situation. Looking at your request:
/My/All/p5
I would go through each route one at a time in my system and ask, "would it match?". The first route where the answer is yes is the one that will match. In your example, you can see that route is the first route. This is why Steven suggests putting more-specific routes first, so they match.
And the Route Debugger I mentioned earlier does this exercise for you. It shows you every route that would match a given request.
I'm trying out ASP.NET MVC routing and have of course stumbled across a problem. I have a section, /Admin/Pages/, and this is also accessible through /Pages/, which it shouldn't. What could I be missing?
The routing code in global.asax:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Pages", // Route name
"Admin/Pages/{action}/{id}", // URL with parameters
// Parameter defaults
new { controller = "Pages", action = "Index", id = "" }
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
// Parameter defaults
new { controller = "Home", action = "Index", id = "" }
);
}
Thanks!
I'd suggest adding an explicit route for /Pages/ at the beginning.
The problem is that it's being handled by the Default route and deriving:
controller = "Pages"
action = "Index"
id = ""
which are exactly the same as the parameters for your Admin route.
For routing issues like this, you should try out my Route Debugger assembly (use only in testing). It can help figure out these types of issues.
P.S. If you're trying to secure the Pages controller, make sure to use the [Authorize] attribute. Don't just rely on URL authorization.
You could add a constraint to the default rule so that the {Controller} tag cannot be "Pages".
You have in you first route {action} token/parameter which gets in conflict with setting of default action. Try changing parameter name in your route, or remove default action name.