Louis Mehring
Louis Mehring

Reputation: 13

Asp Net Mvc Routing without action on multiple Controllers

My Asp Net MVC Application contains 4 Controllers: Home | Training | Diet | Configuration

 routes.MapRoute(
                name: "Default",
                url: "{action}/{id}",
                defaults: new { controller = "Home", action = "Authorize", id = UrlParameter.Optional }
            );

When I want to do a `RedirectToAction("Configurator","Configuration") it tells me the Route isnt found. Picture I tried adding different types of Routes but I never achieved the following scenario:
I just want the URL to doesnt contain the Controllername:
So instead of:
Before: https://localhost/Home/Login
After: https://localhost/Login
but also
Before: https://localhost/Diet/DailyData
After: https://localhost/DailyData

I have a lot of Methods in every Controller so I don't wanna set up for a Route for every Method. Is this possible and how?

Thank you already so much in advance!

Upvotes: 1

Views: 445

Answers (1)

Serge
Serge

Reputation: 43860

Add to RouteConfig after IgnoreRoutes

routes.IgnoreRoute(“{resource}.axd/{*pathInfo}”);
 
routes.MapMvcAttributeRoutes();

after this you can use route attributes and add to the top of each controller

    [Route("[action]")]
    public class HomeController : ControllerBase

     [Route("[action]")]
    public class TrainingController : ControllerBase

....


you will need to add only 4 attributes - one for each controller.

And return default route to it's default

  routes.MapRoute(
        name: “Default”,
        url: “{controller}/{action}/{id}”,
        defaults: new { controller = “Home”, action = “Index”, id = UrlParameter.Optional

it is always a good idea not to touch it. Make your default route like this

[Route("[action]")]
    public class HomeController : ControllerBase
{
[Route("~/Authorize")]
[Route("~/Home/Index")]
public IActionResult Authorize()

Upvotes: 0

Related Questions