cant find Route when action has 2 params - Asp.Net MVC - asp.net-mvc

I have a controller named Blog.
I have an action like this:
[Route("{code:int}/{title?}")]
public virtual ActionResult Index(int code, string title)
{
var postModel = _blogService.Get(code.ToUrlDecription());
return View(postModel);
}
I entered these urls, but all of them returned not found:
localhost:7708/Blog/index/12/post-title;
localhost:7708/Blog/index/12;
localhost:7708/Blog/12/post-title.
I tried to write a route like below, but the result was the same:
routes.MapRoute(
name: "showblogpost", url: "{controller}/{action}/{code}/{title}",
defaults: new {
controller = "Blog",
action = "Index",
title = UrlParameter.Optional
},
namespaces:new string[] { "Web.Controllers" }
);

One thing, you don't need to use both attribute [Route] on action and mapping route.
In your attribute [Route] you have specified only parameters, so route according to it should be localhost:7708/12
by route, specified in MapRoute it should be localhost:7708/showblogpost/12
What I suggest is - remove your attribute, name your route in MapRoute as you want to see in URL, and also you can remove "string title" parameter from action, as it's not used.

Related

Default Route with parameters

I have created a controller and I don't want my default Action or View to be named Index. I created Action in TopicsController as below
[ActionName("Index")]
public ActionResult Topics()
{
var topic = new Topic();
return View("Topics", topic.GetTopics());
}
and it mached to URL xyz.com/Topics.
I tried to apply same philosophy to another controller, named, ModulesController but now I have got parameter.
[ActionName("Index")]
public ActionResult Modules(string id)
{
var topic = new Topic();
return View("Modules", topic.GetTopics());
}
but now it is saying
The resource cannot be found.
what I can do so that this action matches URL like xyz.com/Modules/aaaa?
To access the Url xyz.com/Modules/aaaa change the Action name for the Modules action to aaaa like this:
[ActionName("aaaa")]
public ActionResult Modules(string id)
{
var topic = new Topic();
return View("Modules", topic.GetTopics());
}
FYI - It would be better to avoid naming each action with the ActionName filter. At some point it would become difficult to manage. Instead manage the routes in the RouteConfig like this:
routes.MapRoute(
name: "Modules",
url: "{controller}/{action}/{id}",
defaults: new { controller="Modules", action="Modules", id=UrlParameter.Optional }
);
The following Urls will work for the above route:
xyz.com/Modules/aaaa
xyz.com/Modules/aaaa/123
xyz.com/Modules/aaaa?id=123
Update:
If you want 'aaaa' to be the parameter and want to access the action with xyz.com/Modules/aaaa (where 'aaaa' will be bound as the value to the Id variable) then add the following Route to the route table:
routes.MapRoute(
name: "Modules",
url: "Modules/{id}",
defaults: new { controller="Modules", action="Modules", id=UrlParameter.Optional }
);
Note the value of the Url above.

Identify tenant from the url in multi-tenant asp.net mvc application

I am creating a multi-tenant asp.net application. I want my url to follow
**http://www.example.com/test1/test2/**{tenantName}/{controller}/{action}
**http://www.example.com/test1/**{tenantName}/{controller}/{action}
**http://www.example.com/**{tenantName}/{controller}/{action}
Here the part of the url in bold is fixed (will not change)
{tenantName}=will be logical tenant instance.
I have followed this link
What will be the routing to handle this?
It's as simple as this:
routes.MapRoute(
"MultiTenantRoute", // Route name
"test1/test2/{tenantName}/{controller}/{action}/{id}", // URL with parameters
new { id = UrlParameter.Optional } // Parameter defaults, if needed
);
The part without braces must match. The parts inside the braces will be transfer into route data parameters. I've added an optional parameter id, as you usualy find in the controllers, but you can customize it. You can also give default values to tenantName, controller or action as usual.
Remember that routes are evaluated in the order they're registered, so you should probably register this route before any other.
EDIT after question update
You cannot specify a catch all parameter like this: {*segment} at the beginning of a route. That's not possible. ASP.NET MVC wouldn't know how many segments to include in this part, and how many to be left for the rest of the parameters in the route.
So, you need to add a route for each possible case,taking into account that the first route that matches will be used. So you'd need routes starting with extra parameters like this:
{tenanName}...
{segment1}{tenanName}...
{segment1}/{segment2}/{tenanName}...
Depending on the structre of the expected urls you may need to add constraints to ensure that the route is being correctly matched. This can be done passing a fourth parameter to thw MapRoute method. This is an anonymous class, like the deafults parameter, but the specified value for each parameter is a constraint. These constraints, on their simplest forma, are simply strings which will be used as regular expressions (regex).
If the expected URLs are extremely variable, then implement yout own routing class.
You could define the route as
routes.MapRoute(
name: "TennantRoute",
url: "test1/test2/{tenantName}/{controller}/{action}",
defaults: new { controller = "Home", action = "Index"}
);
and your action must take parameter with name tenantName because you may want make some decision based on that ...for example
public ActionResult Index(string tenantName)
{
return View();
}
example : http://localhost:19802/test1/test2/PrerakT/Home/Index
Please make sure you define this path above the default route for following urls to work
http://localhost:19802/test1/test2/PrerakT/
http://localhost:19802/test1/test2/PrerakT/Home/
http://localhost:19802/test1/test2/PrerakT/Home/index
What if I want test1 and test2 to be changeable ...
routes.MapRoute(
name: "TennantRoute",
url: "{test1}/{test2}/{tenantName}/{controller}/{action}",
defaults: new { controller = "Home", action = "Index" }
);
and
public ActionResult Index(string tenantName, string test1, string test2)
{
return View();
}
as per your update on the question
routes.MapRoute(
name: "TennantRoute1",
url: "test1/test2/{tenantName}/{controller}/{action}",
defaults: new { controller = "Home", action = "Index" }
);
routes.MapRoute(
name: "TennantRoute2",
url: "test1/{tenantName}/{controller}/{action}",
defaults: new { controller = "Home", action = "Index" }
);
routes.MapRoute(
name: "TennantRoute3",
url: "{tenantName}/{controller}/{action}",
defaults: new { controller = "Home", action = "Index" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

Replace default parameter binding without default route values

I have an action in controller like:
public ActionResult Index(string ssn)
{
}
and default route values: {controller}/{action}/{id}
I don't want use url like /Home/Index?ssn=1234. I want use like /Home/Index/1234.
But I also don't want to add new route values for ssn parameter (or custom model binder).
Is there some complete attribute, like [ActionName] but for parameters?
Something like this:
public ActionResult Index([ParameterBinding("id")] string ssn)
{
}
As Darin & Rumi mentioned - there are no built-in attributes, however you can achieve the same affect (across multiple controllers/actions) with a single new Route using the RouteCollection.MapRoute constraints parameter on a single route.
The following route config will apply the "SSN" route to the Foo or Bar controller, any other controller will go through the Default route.
routes.MapRoute(
name: "SSN",
url: "{controller}/{action}/{ssn}",
defaults: new { controller = "Foo", action = "Index" },
constraints: new { controller = "(Foo|Bar)", action = "Index" }
);
// default route
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Edit: Alternatively you could use the ActionParameterAlias library which seems to support what you initially requested.

Unsure about parameter

I am currently working on a beginner's MVC tutorial. I was wondering if anyone could explain how or where the parameters of this method are chosen?
public ActionResult Details(int id)
{
var album = storeDB.Albums.Find(id);
return View(album);
}
There are 2 ways your id parameter could be populated:
http://www.example.com/{Controller}/Details/{id}
or
http://www.example.com/{Controller}/Details?id={id}
where {Controller} is the name of your Controller, eg. The name of HomeController.cs would be "Home"
and where {id} is an int.
you're working with the default route I guess, so you gonna find in the Global.asax file the follow code:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
your route is that! where "id" is a optional parameter, suppose that your controller name is Album, so test http://mySite/Album/Details/10
you get a request where 10 is your Id parameter specify on the action Details

How can I get the route name in controller in ASP.NET MVC?

ASP.NET MVC routes have names when mapped:
routes.MapRoute(
"Debug", // Route name -- how can I use this later????
"debug/{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = string.Empty } );
Is there a way to get the route name, e.g. "Debug" in the above example? I'd like to access it in the controller's OnActionExecuting so that I can set up stuff in the ViewData when debugging, for example, by prefixing a URL with /debug/...
The route name is not stored in the route unfortunately. It is just used internally in MVC as a key in a collection. I think this is something you can still use when creating links with HtmlHelper.RouteLink for example (maybe somewhere else too, no idea).
Anyway, I needed that too and here is what I did:
public static class RouteCollectionExtensions
{
public static Route MapRouteWithName(this RouteCollection routes,
string name, string url, object defaults, object constraints)
{
Route route = routes.MapRoute(name, url, defaults, constraints);
route.DataTokens = new RouteValueDictionary();
route.DataTokens.Add("RouteName", name);
return route;
}
}
So I could register a route like this:
routes.MapRouteWithName(
"myRouteName",
"{controller}/{action}/{username}",
new { controller = "Home", action = "List" }
);
In my Controller action, I can access the route name with:
RouteData.DataTokens["RouteName"]
If using the standard MapRoute setting like below:
routes.MapRoute( name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
...this will work in the view...
var routeName = Url.RequestContext.RouteData.Values["action"].ToString();
You could pass route name through route values using default value of additional parameter:
routes.MapRoute(
name: "MyRoute",
url: "{controller}/{action}/{id}",
defaults: new { routeName = "MyRoute", controller = "Home", action = "Index", id=UrlParameter.Optional }
);
Then, it is possible to get passed value from controller context:
string routeName = ControllerContext.RouteData.Values["routeName"].ToString();
This does not directly answer the question (if you want to be pedantic); however, the real objective seems to be to get a route's base URL, given a route name. So, this is how I did it:
My route was defined in RouteConfig.cs as:
routes.MapRoute(
name: "MyRoute",
url: "Cont/Act/{blabla}",
defaults: new { controller = "Cont", action = "Act"}
);
And to get the route's base URL:
var myRoute = Url.RouteUrl("MyRoute", new { blabla = "blabla" }).Replace("blabla", "");
It gave me the route's base URL that I wanted:
/Cont/Act/
Hope this helps.
An alternative solution could be to use solution configurations:
protected override OnActionExecuting()
{
#if DEBUG
// set up stuff in the ViewData
#endif
// continue
}
There shouldn't really ever be a need to reference the route name like this - which I suppose is why MVC makes it so difficult to do this sort of thing.
another option - use MapRoute with string[] namespaces argument, then you can see your namespaces as RouteData.DataTokens["Namespaces"]

Resources