ServiceRoute in ASP.NET MVC with areas intercepts ActionLink to Home - asp.net-mvc-3

I have an MVC 3 application with areas, and I am exposing a service from a specific area and controller. The routing to this service is defined inside the AreaRegistration like this
public class AreaAreaRegistration : AreaRegistration
{
public override string AreaName
{
get { return "Area"; }
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.Routes.Add(
new ServiceRoute("Area/Controller/Service",
new NinjectServiceHostFactory(), typeof(MyService)));
// ....
}
}
In my Global.asax.cs I only define a default route
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
In my _Layout.chshtml I have a link to my home page, where I give an empty area, and I expect it to find the Index action in the HomeController in the Controllers folder at the top (outside the Areas folder):
#Html.ActionLink("Home", "Index", "Home", new { area = "" }, null)
For some reason this ActionLink renders as
~/Area/Controller/Service?action=Index&controller=Home
If I comment out the ServiceRoute, the same ActionLink points to ~/ which is what I expect.
Any ideas how to fix this routing issue? The only workaround I have found is to use this instead:
Home

We were having this exact same problem. The order of route registration appears to be the issue, in that routes from areas will be registered before routes from the global.asax code.
To fix this issue, allowing the URL route to the service as well as preventing the postback from being targeted at the service URL try moving the ServiceRoute addition into the Global.asax.cs after the other route is registered.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
context.Routes.Add(
new ServiceRoute("Area/Controller/Service",
new NinjectServiceHostFactory(), typeof(MyService)));
}
This worked for us, but does of course come at the overhead of putting code pertaining to the area in the main project.

Related

Whats wrong with my routes and actions?

I recently asked a question based on how to create pages based on the content table which contains the following: Title and Content. I followed the steps, to my understanding, in the answer that was given.
I created a route like so:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
routes.MapRoute(
"ContentManagement",
"{title}",
new { controller = "ContentManagement", action = "Index", title = "{title}" }
);
}
I am assuming I can do routes like this? where I can set up multiple routes? I am also assuming I can pass the title to to the controller action like I have done?
I then created the model:
namespace LocApp.Models
{
public class ContentManagement
{
public int id { get; set; }
[Required]
public string title { get; set; }
public string content { get; set; }
}
}
from that I created a controller with an index action that looks as such:
public ViewResult Index(string title)
{
using (var db = new LocAppContext())
{
var content = (from c in db.Contents
where c.title == title
select c).ToList();
return View(content);
}
}
So then I created some content with the title of "bla" so when I visit site.com/bla I get an error that it cant find "bla/"
Can some one tell me what I am doing wrong? I would also, if you are familiar with the default layout of a asp.net mvc project with the tabs at the top, create a set of tabs that lead to the pages, based on the title in the database
The main issue is that when you are using the title, the routing engine is matching it to the first route and trying to find a controller by that title. We have implemented something similar and found that by explicitly defining what controllers are valid for the default route, it then processed request appropriately. I gave an example of the controllers that we allow to fit our default route below (Home, Help and Error).
You probably also want to prevent people from giving the content the same TITLE as your root level controllers as that would blow this up pretty well.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new {controller = "Home", action = "Index", id = UrlParameter.Optional},
new {controller = "Home|Error|Help"},
new[] {"UI_WWW.Controllers"});
routes.MapRoute(
"ContentManagement",
"{title}",
new {controller = "ContentManagement", action = "Index"});
}
}

Custom route does not work in ASP.net MVC 3

I am trying to implement my custom route in ASP.net MVC 3 but I get this error:
The resource cannot be found.
global.asax
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"mycontroller", // Route name
"{controller}/{name}", // URL with parameters
new { controller = "MyController", action = "Search" } // Parameter defaults
);
}
MyController.cs
public class MyController : Controller
{
public ActionResult Search(string name)
{
return Content(name);
}
}
Try this instead:
routes.MapRoute(
"mycontroller", // Route name
"mycontroller/{name}", // URL with parameters
new { controller = "My", action = "Search", } // Parameter defaults
);
MyController won't be found because you don't have a controller named MyControllerController. By virtue of inheriting from Controller the convention will be looking for the URL token + "Controller".
Cheers.
Try changing it to
routes.MapRoute(
"mycontroller", // Route name
"{controller}/{name}", // URL with parameters
new { controller = "My", action = "Search", } // Parameter defaults
);
Please register it in Global.asax file

ASP.NET MVC Areas routing not working with default route

I am trying to separate my MVC project into multiple areas. So i have 3 areas 1) crm 2)services 3) Web. I want PublicWeb to be my default one. that means it should be accessed like www.mysitename.com/mycontroller/myaction( no area name inbetween) and other two to be accessed with the area name (www.mysitename.com/crm/mycontroller/myaction). What routing/ Area configuration i should have ? I tried AreaRegistration.RegisterAllAreas(); and it works only for my default one (web). When i access the other 2, it threw 404 error.
I tried to register indidually like the below one
var area2reg = new crmAreaRegistration();
var area2context = new AreaRegistrationContext(area2reg.AreaName, RouteTable.Routes);
area2reg.RegisterArea(area2context);
var area1reg = new webAreaRegistration();
var area1context = new AreaRegistrationContext(area1reg.AreaName, RouteTable.Routes);
area1reg.RegisterArea(area1context);
Then my publicweb works. But when i access my forum it threw this error,
Multiple types were found that match the controller named 'home'. This can happen if the route that services this request ('crm/{controller}/{action}/{id}') does not specify namespaces to search for a controller that matches the request. If this is the case, register this route by calling an overload of the 'MapRoute' method that takes a 'namespaces' parameter.
My RegisterArea function for web is this
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"web_default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
and the one for crm is this
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"crm_default",
"crm/{controller}/{action}/{id}",
new { controller = "home", action = "Index", id = UrlParameter.Optional }
);
}
}
How do i handle this ?
From what I can see the area routes look fine. Did you update the default route in your Global.asax to send requests to the web area?
Something like:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}",
new { area = "web", controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
I think Jonathan S's solution is definitely worth a try, but you might consider a different approach. That would be to put your web files in the default locations. The routing engine would not look in the Area's for those files when no Area is part of the request.

ASP.net MVC routing with optional first parameter

I need to provide following functionality for one of the web sites.
http://www.example.com/[sponsor]/{controller}/{action}
Depending on the [sponsor], the web page has to be customized.
I tried combination of registering the routes with Application_Start and Session_Start but not able to get it working.
public static void RegisterRoutes(RouteCollection routes, string sponsor)
{
if (routes[sponsor] == null)
{
routes.MapRoute(
sponsor, // Route name
sponsor + "/{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
}
Also, the default behavior without [sponsor] should also function.
Can someone please let me know if it is technically feasible to have an optional first parameter in the MVC3 URL. If yes, please share the implementation. Thank you.
Updated Code
After making the changes as suggested by Sergey Kudriavtsev, the code works when value is given.
If name is not provided then MVC does not route to the controller/action.
Note that this works only for the home controller (both and non-sponsor). For other controllers/actions, even when sponsor parameter is specified it is not routing.
Please suggest what has to be modified.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"SponsorRoute",
"{sponsor}/{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
"NonSponsorRoute",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional, sponsor = string.Empty }
);
}
Action Method
public ActionResult Index(string sponsor)
{
}
In your case sponsor should not be treated as a constant part of URL, but as a variable part.
In Global.asax:
public static void RegisterRoutes(RouteCollection routes)
{
...
routes.MapRoute(
"SponsorRoute",
"{sponsor}/{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
"NonSponsorRoute",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional, sponsor=string.Empty }
);
...
}
In your controllers, for example, HomeController.cs:
namespace YourWebApp.Controllers
{
public class HomeController : Controller
{
public ActionResult Index(string sponsor)
{
// Here you can do any pre-processing depending on sponsor value, including redirects etc.
}
...
}
}
Note that type of this parameter will always be System.String and the name of route template component {sponsor} must exactly match the name of action parameter string sponsor in your controllers.
UPD: Added second route for non-sponsor case.
Please note that such setup will complicate your logic, because you might confuse different urls, for example URL
http://www.example.com/a/b/c
could be matched by both routes: first one will have sponsor=a, controller=b and action=c; second one will have controller=a, action=b and id=c.
This situation can be avoided if you specify more strict requirements to URLs - for example, you may want IDs to be numerical only. Restrictions are specified in fourth parameter of routes.MapRoute() function.
Another approach for disambiguation is specifying separate routes for all of your controllers (usually you won't have much of them in your app) before generic route for sponsors.
UPD:
Most straightforward yet least maintainable way to distinguish between sponsor and non-sponsor routes is specifying controller-specific routes, like this:
public static void RegisterRoutes(RouteCollection routes)
{
...
routes.MapRoute(
"HomeRoute",
"Home/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional, sponsor=string.Empty }
);
routes.MapRoute(
"AccountRoute",
"Account/{action}/{id}", // URL with parameters
new { controller = "Account", action = "Index", id = UrlParameter.Optional, sponsor=string.Empty }
);
...
routes.MapRoute(
"SponsorRoute",
"{sponsor}/{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
...
}
Note that here all controller-specific routes must be added before SponsorRoute.
More complex yet more clean way is implementing RouteConstraints for sponsor and controller names as described in answer from #counsellorben.
In my case, I've resolved this issue using the following two routers:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "MultiCulture",
url: "{culture}/{controller}/{action}",
defaults: new { controller = "Home", action = "Index" },
constraints: new { culture = new CultureConstraint(CultureFactory.All.Select(item => item.UrlPrefix).ToArray()) }
).RouteHandler = new MultiCultureMvcRouteHandler();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}",
defaults: new { controller = "Home", action = "Index" }
);
}
}
Where CultureConstraint class looks like below:
public class CultureConstraint : IRouteConstraint
{
private readonly string[] values;
public CultureConstraint(params string[] values)
{
this.values = values;
}
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary routeValues, RouteDirection routeDirection)
{
string value = routeValues[parameterName].ToString();
return this.values.Contains(value);
}
}
And MultiCultureMvcRouteHandler like this:
public class MultiCultureMvcRouteHandler : MvcRouteHandler
{
protected override IHttpHandler GetHttpHandler(System.Web.Routing.RequestContext requestContext)
{
var culture = CultureManager.GetCulture(requestContext.RouteData);
if (culture != null)
{
var cultureInfo = new CultureInfo(culture.Name);
Thread.CurrentThread.CurrentUICulture = cultureInfo;
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(cultureInfo.Name);
}
return base.GetHttpHandler(requestContext);
}
}
In addition to adding a second route before the default route, as Sergey said in his answer, you also must add a RouteConstraint to the initial route, to enforce that the {sponsor} token is the name of a valid sponsor.
You can use the RouteConstraint in this answer: Asp.Net Custom Routing and custom routing and add category before controller
Remember that you must also enforce a rule that a sponsor name cannot be the same as any of your controller names.
i will show you in simple example you don't have to change in Route.config.cs
only you have to do in Route.config.cs just put in
Optional URI Parameters First and Default Values
Route.config.cs
routes.MapMvcAttributeRoutes();
Controller
[Route("{Name}/Controller/ActionName")]
public ActionResult Details(string Name)
{
// some code here
return View();
}
Results
localhost:2345/Name/controllername/actionname/id(optional)

Unable to understand the Asp.net MVC routing

I have added the following route to my global.asax file :-
routes.MapRoute(
"Admin_Route",
"Admin/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional },
new[] { "PriceCompare.Admin.Controllers" }
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new[] { "PriceCompare.Controllers" }
);
The admin controllers i.e. ManageCatsController, ManageBrandsController, etc. reside in PriceCompare.Admin.Controllers namespace and other general controllers reside in PriceCompare.Controllers namespace.
The problem is that i am able to visit all the controllers by adding Admin/ in front of them, irrespective of whether they are in PriceCompare.Admin.Controllers namespace.
Also, I am able to visit admin controllers directly without prefixing Admin/.
Why is this happening. Am i misunderstanding the routing behaviour.
You need to register your Admin area.
When I have registered routes for areas I've always done it like this:
Inside App/Areas/Admin folder create an AdminAreaRegistration.cs file with this in it...
using System.Web.Mvc;
namespace AppName.Areas.Admin
{
public class AdminAreaRegistration : AreaRegistration
{
public override string AreaName
{
get
{
return "Admin";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Admin",
"Admin/{controller}/{action}/{id}",
new { controller="Home", action = "Index", id = UrlParameter.Optional },
new string[] { "AppName.Areas.Admin.Controllers" }
);
}
}
}
Now do this in Global.asax:
protected void Application_Start()
{
// Add this next line
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
// Add any other stuff (like IoC or whatever)
}
And only register your normal routes in RegisterRoutes in Global.asax, like this:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // Parameter defaults
new string[] { "AppName.Controllers" }
);
}
I would also recommend keeping the Area part inside your Admin namespace (so calling it PriceCompare.Areas.Admin.Controller in your case) as it will make life a lot easier later on when.
Please try this and let me know if it works :-)

Resources