I've created a new ASP.NET MVC 3 internet application in Visual Web Developer 2010 Express, and I have noticed that with this default template, the path localhost:port/Home shows the same content as localhost:port/
Is there a way to remove the /Home? I would only like localhost:port/ to be the landing page.
Both urls work because that's how the default route has been defined in Global.asax:
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
This means that all of /, /Home and /Home/Index will land to the HomeController/Index action. So in fact when you are request / it is the exact same action being executed.
You can modify it like so:
routes.MapRoute(
"Default",
"{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Of course by doing this the only controller and action you will ever be able to run in your application will be the HomeController and Index action. No other action or controller will be ever accessible as you don't provide any means in the url to specify them. So I would leave the default routes as is because they allow to handle 99% of the cases unless you have some specific requirements.
The other guys are correct. However they dont really tell you a way around it. One way to get better control of the routes is as follows
Do something like below in the Register routes method
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
var controllers = typeof(MvcApplication).Assembly.GetTypes().Where(t => !t.IsAbstract && t.Navigate(_ => _.BaseType).Any(_ => _ == typeof(Controller)));
foreach (var controller in controllers)
{
var actions = controller.GetMethods().Where(m => m.HasAttribute<RouteAttribute>()).Select(m => new { Method = m, Attribute = m.GetAttribute<RouteAttribute>() }).ToArray();
foreach (var action in actions.OrderBy(m => m.Attribute.Path.Count(c => c == '{')))
routes.MapRoute(string.Format("{0}.{1}", controller.Name, action.Method.Name), action.Attribute.Path.TrimStart('/'), new { controller = controller.Name.Replace("Controller", ""), action = action.Method.Name });
}
and then decorate your controller methods with a route attribute that defines exactly what the route should be. You have to make the route attribute yourself, it cna be pretty simple just an attribute with a string parameter . In this fashion you can set any controller method to have any route you like.
Related
I have Created a new Controller called Consultants. Then I create action method Index()..
I gave route like the following,
routes.MapRouteLowercase(
"consultants",
"consultants/index",
new { controller = "Consultants", action = "Index" }
);
In view, ActionLink method is,
<%: Html.ActionLink("Consultant Home", "Index", "Consultants", null, new { title = "Back home" })%>
But it is not routing. It is showing Resource cannot be find
Please correct my issues...
It looks like you've created a custom RouteCollectionExtensions called MapRouteLowercase (or at least I'm not familiar with it). I'd test that to make sure it's working as you expect by changing your route to this:
routes.MapRoute(
"consultants",
"consultants/index",
new { controller = "Consultants", action = "Index" }
);
Otherwise, you may have another route map causing issues, so make sure that route config is at the very top of your routing. Order plays an important role in how the route engine determines the correct url when searching for patterns. So order from specific to general.
For example, if you did something like this, it would cause issues with your current route:
routes.MapRoute(
"dateRoute",
"consultants/{date}",
new { controller = "Consultants", action = "Dates", date = UrlParameter.Optional }
);
I'm trying to achieve this goal of changing my apps routes to look like this:
hxxp://host/MyController/Widgets/3/AddWhatsit
The view for this route would help a user add a Whatsit to Widget 3.
Similarly, I would expect the route to create a new Widget to be:
hxxp://host/MyController/Widgets/Create
I've created separate routes to try and facilitate this. They are:
routes.MapRoute("DefaultAction",
"{controller}/{action}",
new {controller = "Home", action = "Index"});
routes.MapRoute("Default",
"{controller}/{id}/{action}",
new {controller = "Home", action = "Index", id = UrlParameter.Optional});
The problem I'm having is that when I browse to the Index page for Widgets (/MyController/Widgets, matching the "DefaultAction" route) Any ActionLinks that would introduce a new url parameter that's not part of that route gets turned into a querystring value. So, for example, the edit link for Widget 3 would render as:
Widget/Edit?id=3
instead of (what I would prefer):
Widget/3/Edit
I guess I understand that I'm messing things up by not putting my (optional) id param at the end of the route.
Should I suck it up and just leave id at the end of the route?
It is possible to achieve this. To get anchor link looking like /Home/1/Index, set routes like:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Custom",
url: "{controller}/{id}/{action}"
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
And then, in the View:
#Html.ActionLink("Here", "Index", "Home", new { id = 5 }, null)
And you get link rendered like this:
Here
Quirk is to constrain custom route. I removed defaults in this case, they do not make sense. And order of routes, of course.
I believe you need to change the order of your routes. Remember, that MVC looks down the route list and picks the First matching route. Your second route with the ID parameter is more specific and as such, should come first in your routing table.
Even though you have specified an ID parameter in your ActionLink, you have also specified a controller and an action. Therefore, the first route is being chosen by the RoutingEngine.
Lastly, remove the optional parameter for the ID attribute. Since you want that route to be chosen when you have an Id, then you do not want that to be an optional parameter, you want it to be required to match that route.
routes.MapRoute("Default","{controller}/{id}/{action}",
new {controller = "Home", action = "Index"});
routes.MapRoute("DefaultAction", "{controller}/{action}",
new {controller = "Home", action = "Index"});
I'm building a small MVC application. After a user logs in I want his/her route to display:
www.appname.com/username/
Underneath of course same action is called for each user e.g. /home/index. How do I write my MapRoute to achieve that and what other code(attributes) should I use?
Add this rout to your routes in global.asax.cs file
routes.MapRoute(
"RouteName", // Route name
"FixedUrlSegment/{UserName}/{Controller}/{action}/{id}/", // URL with parameters
new { controller = "ControllerName",
action = "ActionName",
id=UrlParameter.Optional
},
);
I think you should use a fixed segment as start-up point for your route to distinguish it from default or other routes
of course in log in action method you must redirect to that new route
return RedirectToRoutePermanent("RouteName", new { username = "UserName",
action = "Index",
controller = "Home",
id="userId"
}
);
// remember id is not required for that route as mentioned in global file
this example will redirect your page to url
www.appname.com/FixedUrlSegment/loggedusername/home/index/loggeduserid
I'm having problems when using this route:
routes.MapRoute("ProductIndex", "pr-{key}", new { controller = "Home", action = "Product" });
When the key contains 'pr-', the route doesn't work.
Example: http://.../pr-my-product-key-with-pr-key
Routes don't work the way you want them to work, but it's easily converted
change your route to:
routes.MapRoute(
"ProductIndex",
"pr/{key}",
new { controller = "Home", action = "Product" });
and use:
http://.../pr/my-product-key-with-pr-key
or, if you really want to use that "way" you need to override the Initialization method of your main controller are check the link with StartWith() and redirect to the proper Controller.
In my routing I would like to have something like not found route handler.
For example I have created one mapping like
routes.MapRoute(
"default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id="" }
);
routes.MapRoute(
"Catchall",
"{*catchall}",
new { controller = "Home", action = "Lost" }
);
but when user inserts address something like /one/two/three/four/bla/bla it will be cached with the Catchall mapping.
But when user inserts something that should match with default mapping,
(like /one/two/ ,but this controller or action is not implemented)
I would want that Catchall mapping would accept this request,
because all other mappings failed. But instead of this I get an error.
Should I override some mapping handlers to catch the exception if controller or action getting an exception?
The issue here is that it's not the Route's responsibility to make sure that "one/two" maps to a file. That responsibility falls to the ViewEngine. Since "one/two" is a valid route, it will be chosen.
If you want to handle the error of an invalid route, what I would recommend you do is simply use the built in ErrorHandling "page" to display whatever message you would have done in the Catchall.
I don't think this is the best solution, but you could always be more specific on your routes:
routes.MapRoute(
"home and action",
"home/index/{id}",
new { controller = "Home", action = "Index", id="" }
);
... repeat for the rest of your actions ...
routes.MapRoute(
"article catch all",
"home/{article}",
new { controller = "Home", action = "ArticleSearcher", article="" }
);
This would attempt to match a direct action, and if no action is found, pass what would normally be the {action} part of the default route to the 'ArticleSearcher' action as an article string parameter.
The downside is having to explicitly create each controller/action route.