Reputation: 33
Is it possible the accomplish route config in MVC without fixed value? Does this method affects other routes too?
For example, i want to do;
website.com/category/my-title
website.com/other-category/another-title
website.com/another-category/and-another-title
When i try something like this;
routes.MapRoute(
name: "Content",
url: "{category}/{title}",
defaults: new { controller = "Main", action = "Content"}
);
Sometimes it works as expected but mostly it cause confusion. Some urls for default route and other static pages can not be found because mvc thinks its still category/title kinda url it is. I can fix this with some "fixed" value like
routes.MapRoute(
name: "Content",
url: "fixed/{category}/{title}",
defaults: new { controller = "Main", action = "Content"}
);
Is it possible to do this without fixed value and use another route's in mvc?
Upvotes: 1
Views: 147
Reputation: 6185
Is it possible to do this without fixed value and use another route's in mvc?
Unfortunately, if you want to have domain.com/{category}/{title}
you'll have conflict with a lot of routes, especially the default route which accepts both string controller name and string action name.
That fixed value is the easiest fix to the issue and it's the only real fix, my suggestion below is somehow a work-around;
If you want to retain that route domain.com/{category}/{title}
, you could add an if statement to your Content action method that checks if that category belongs to a Controller name.
public ActionResult Content(string category, string title)
{
// initialize list of controller names, better if this from a static function
List<string> controllerNames = new List<string>(){ "Home","Main","Product" };
// check if category parameter matches a controller name
var check = controllerNames.FirstOrDefault(s=>s==category);
// if it matches a controller name, redirect
if(check != null)
{
return RedirectToAction(title,category);
}
else
{
// do what Content action normally does
}
}
Upvotes: 1
Reputation: 456
I assume you need attribute routing more than changing it in whole project:
Use this before your [HttpGet] method:
[Route("{category}/{title}")]
More information is provided here if I understood correctly your issue.
Upvotes: 1