Old
I have created a new route for my application, which is as follows
routes.MapRoute(
name: "Default",
url: "{custom}/{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
constraints: new { custom = new RouteValidation() }
);
While it works, it only works for Home/Index. When I want to go to Home/Login it just reloads the page. This worked before the new route.
My question, do I need to create a new route for every method or is there a better way to do this?
Update
What I would like to get is an url like this localhost/{custom}/{controller}/{action}/{id}
where 'custom' is a unique id to get information from a company.
1234 = company 'A' -> localhost/1234/Home/Index
0987 = company 'B' -> localhost/0987/Home/Index
Here is my complete routing
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Route1",
url: "{custom}/{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
constraints: new { custom = new CustomerServiceModule.Helpers.RouteValidation() }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
Here is my RouteValidation, this check whether the {custom}
is a valid id or not, this works.
public class RouteValidation : IRouteConstraint
{
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
if (routeDirection == RouteDirection.IncomingRequest)
{
//returns true if the 'custom' is valid else false
return CheckPublicationUniqueID(values["custom"].ToString());
}
return false;
}
}
And here are some routes of the application
Index/Home
Index/Login
Subscription/Index
Subscription/Edit/{id}
Subscription/Details/{id}
Invoice/Index
History/Index
The problem that I have is that if I navigate to lets say 'Subscription/Index' the 'custom' is gone from the url and if I remove the default route it does not go to any of the above named urls.
Well I found the solution for my problem.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"CompanyRouteWithoutParameters",
"{company}/{controller}/{action}",
new { controller = "Home", action = "Index" },
new { company = new RouteValidation() }
);
routes.MapRoute(
"CompanyRouteWithParameters",
"{company}/{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}