Url.Action does not use desired route for output - asp.net

I have the following route definitions in my MVC3 website:
routes.MapRoute(
"FB", // Route name
"fb/{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
).RouteHandler = new RH();
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
My custom "RH" handler's code is
public class RH : MvcRouteHandler
{
protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
{
//here I store somewhere that 'fb' prefix is used, so logic is different in some places
return base.GetHttpHandler(requestContext);
}
}
What I want to achieve, that when my website is accessed with the 'fb' subpath-prefix, then my website-logic executes a little bit different way.
The problem is, that when I access my site normally (eg. http://localhost), then when I execute
Url.Action('action' 'controller')
, then the output is "http://localhost/fb/controller/action".
I want to achieve, that when my site was accessed with 'fb' prefixed subpath, then my Url.Action calls output /fb/controller/action path, and if I access the website normally (without 'fb' prefix subpath), then Url.Action calls output /controller/action
The main thing, that /fb/controller/actions have to route to the same controllers/actions as when the site is accessed via /controller/action format.
The 'fb' route is just needed to store some temporary info when 'fb' prefix i used.

Seems I found a solution based on this link (MVC 3 Routing and Action Links not following expected contextual Route), new path-placeholder introduced and constraint added.
Maybe it's not good enough, or you know better than this, but seems to work for me:
routes.MapRoute(
"FB", // Route name
"{path}/{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // Parameter defaults
new { path = "fb" }
).RouteHandler = new RH();
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);

Related

In asp.net MVC if the url has a parameter , does the route have to be registered?

In my limited (2 weeks) experience in asp.net MVC3, for most action methods, I have never needed to add a route registration. But I have noticed that if the action method has an input parameter, then I can't access the method with a url of the form www.mysite.com/myController/myAction/myParameter1/myParameter2/myParameter3 (without the ? mark ) unless I map the route. Is that how its supposed to be?
By default, you already have registered route:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
it accepts one parameter, named id, so your action:
public ActionResult MyAction(string id)
will "catch" the request:
www.mysite.com/MyController/MyAction/parameter_value
and id will get value "parameter_value".
If you need more than one parameter (or parameter has to be names something else than "id"), then you have to register new route.
In case when you have 2 parameters, you will register route like this:
routes.MapRoute(
"Default",
"{controller}/{action}/{parameter1}/{parameter2}",
new { controller = "Home", action = "Index", parameter1 = UrlParameter.Optional, parameter2=UrlParameter.Optional }
);
and your action might be:
public ActionResult MyAction(string parameter1, int? parameter2)
Yeah, you need to register the route customizing the route in global.asax according to your requirement.You have to register the route in following way:
routes.MapRoute(
"routeName", // Route name
"{controller}/{action}/{myParameter}", // URL with parameters
new { controller = "Home", action = "Index", myParameter= "" } // Parameter defaults
);
So with above route, it ensures that whenever your url goes in above format, the parameter right after "action/" will be taken as parameter.....
For more than one parameter in your url, you can register like this:
routes.MapRoute(
"routeName", // Route name
"{controller}/{action}/{myParameter1}/{myParameter2}/{myParameter3}", // URL with parameters
new { controller = "Home", action = "Index", myParameter1= "", myParameter2= "", myParameter3= "" } // Parameter defaults
);

MVC 3 Routes: Dynamic content from home controller - Where am I going wrong?

My Setup
I have a set of controllers in the normal fashion, which have their usual CRUD action methods inside them. Examples of these controllers are Testimonials, Galleries, and FAQs. These have backing models in Entity Framework, such as Testimonial, Gallery and FAQ, respectively.
You get to these by this sort of URL: /Galleries/Edit/2
All good so far, and all by default conventions...
I also have a set of pages that need to have editable content in them, and these have their content populated from a database via Entity Framework. They use an EF model behind them called "Page". This has a content property (html), and a name property so that I can match the incoming request. These pages are the Home, About and Prices pages.
I have chosen the Home controller to do this - I intend to have the index Action work out which Page to load from the DB by a name parameter:
[AllowAnonymous]
public ActionResult Index(string name = "Home")
{
// look up the page by name in the DB.
var model = context.Pages.FirstOrDefault(p => p.Title == name);
// trap errors.
if (model == null)
{
return RedirectToAction("NotFound", "Error", new { aspxerrorpath = name } );
}
// normal path
return View(model);
}
So, I could in theory add new items to the Pages table/DbSet and these would get mapped properly to this controller and action. I will then add an edit action for admin to edit the content that has the same signature as the index action above.
The Problem
The issue comes with Routing requests...
I had 2 initial routes:
routes.MapRoute("DynamicAccess",
"{name}/{action}",
new { controller = "Home", action = "Index" });
routes.MapRoute("Default",
"{controller}/{action}/{id}",
new { controller = "Home", action="Index", id=UrlParameter.Optional});
This fails when I go to "Galleries/", as it goes through the Home controller each time, and fails if I swap them around. I was also getting requests for Scripts/ folder through to the home controller too....
My Temporary Solution
My current routes now look like this:
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("favicon.ico");
routes.MapRoute("Gallery",
"Gallery/{action}/{id}",
new { controller = "Galleries", action = "Index", id = UrlParameter.Optional });
routes.MapRoute("Testimonials",
"Testimonials/{action}/{id}",
new { controller = "Testimonials", action = "Index", id = UrlParameter.Optional });
routes.MapRoute("FAQs",
"FAQs/{action}/{id}",
new { controller = "FAQs", action = "Index", id = UrlParameter.Optional });
routes.MapRoute("DynamicAccess",
"{name}/{action}",
new { controller = "Home", action = "Index" });
routes.MapRoute("Default",
"{controller}/{action}/{id}",
new { controller = "Home", action="Index", id=UrlParameter.Optional});
routes.MapRoute("Root",
"",
new { controller = "Home", action = "Index" });
routes.MapRoute("AdminAccess",
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // Parameter defaults
new { authenticated = new AuthenticatedAdminRouteConstraint() });
You can see here that I've had to declare a route for each of my static pages above the route for the dynamically resolved Home Route.
Question
This looks clumsy to me - having to add each non-dynamic page to my routes table.
Can anyone point me to a cleaner way of doing this please?
Thanks in advance.
Why not put a constraint on your static routes, which will allow routes that don't match to fall through to the dynamic route?
routes.MapRoute("default",
"{controller}/{action}/{id}",
new {controller="home", action="index", id=UrlParameter.Optional},
new {controller="^(|home|gallery|testimonial|faq)$"});
routes.MapRoute("dynamic",
"{name}/{action}",
new {controller="home", action="index"});
You will have to change your controllers to match the singular name in the constraint but other than that, it ought to work.

asp.net MVC3 global route and hardcoded routes

I have an application that I am using a global route to query for the current path and return page specific data. I have the routes setup like this...
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Pages",
"Pages",
new { controller = "Pages", action = "Index" });
routes.MapRoute(
"Navigation",
"Navigation",
new {controller = "Navigation", action = "Index"});
routes.MapRoute(
"Default", // Route name
"{*url}", // URL with parameters {controller}/{action}/{id}
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
The problem I am facing is when I go to /Pages to try and add new pages, the PageController fires like it is supposed to, but when debugging, after going to /Pages the app then makes a request for the HomeController. Am I missing something in my routing setup?
The Default route is firing because of the {*url}. So any page that's not /Pages, will go to the default route.
I need more info, but if you're trying to do /Pages/whatever, then you need to add an optional parameter on your Pages route:
routes.MapRoute(
"Pages",
"Pages/{page}",
new { controller = "Pages", action = "Index", page = UrlParameter.Optional });
Your default route is incorrect. It should look like the default route as defined when you open a new MVC 3 project, like so:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
The problem is that the default route you defined will not parse any requests which reach it.

Asp.net mvc Details method

I am working on a project, where I have used the default routing
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}/{name}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional, name = UrlParameter.Optional } // Parameter defaults
);
I have a users controller and methods like Index, create and details
I dont want to create links like http://mysite/users/details/111/somename
instead i want to create http://mysite/users/111/somename
like stackoverflow kind of url.
I know I can achieve by registering a route like this (before default route)
routes.MapRoute(
"UsersDetails", // Route name
"Users/{id}/{name}", // URL with parameters
new { controller = "Users", action = "Details", id = UrlParameter.Optional, name = UrlParameter.Optional } // Parameter defaults
);
but then all my other urls start creating problem. for example if i have url
http://somesite/users/registersuccess
Is there in workaround for this issue, or I should register all the urls.
Regards
Parminder
You'd need a constraint on your id parameter for your routes:
routes.MapRoute(
"UsersDetails",
"Users/{id}/{name}",
new { controller = "Users", action = "Details", id = UrlParameter.Optional, name = UrlParameter.Optional },
new { id="\d+" }
);
Then your other routes wouldn't be affected.

Routing table is not working

HI I have the following routing table
routes.MapRoute(null,
"Save", // Route name
new { controller = "Package", action = "Save"} // Parameter defaults
);
routes.MapRoute(
"Package", // Route name
"{controller}/{action}/{name}/{p}", // URL with parameters
new { controller = "Package", action = "Index", name = UrlParameter.Optional, p = UrlParameter.Optional } // Parameter defaults
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
When i am typing the path /Package/Save it is showing me page not found.
Can anybody please tell me what i am doing wrong?
THanks
The first route is configured incorrectly - name of route, then the pattern and then the defaults.
Also make sure you have a Package controller and a Save action method on it.

Resources