dakt
dakt

Reputation: 650

ASP.NET MVC route

I have only default route enabled:

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

Which will resove paths like: hostname/Home/Index, hostname/Home/Foo, hostname/Home/Bar/23 just fine.
But I must also enable route like this: hostname/{id} which should point to:
Controller: Home
Action: Index
{id}: Index action parameter "id"

Is such a route even possible?

Upvotes: 0

Views: 84

Answers (4)

tony
tony

Reputation: 359

Have you tried to play around with AttributeRouting package?

Then your code will look like this

    [GET("/{id}", IsAbsoluteUrl = true)]
    public ActionResult Index(string id) { /* ... */ }

Upvotes: 0

dakt
dakt

Reputation: 650

Since I'm short on time, I have configured route for every action. Luckly there are not many of them. :)

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

        routes.MapRoute(
            name: "IndexWithOutParam",
            url: "",
            defaults: new { controller = "Home", action = "Index" }
        );

        routes.MapRoute(
            name: "Login",
            url: "Home/Login",
            defaults: new { controller = "Home", action = "Login" }
        );

So last route was repeated for ever other action. Not sure if it can be done better, but it works.

Upvotes: 0

Vishal Sharma
Vishal Sharma

Reputation: 2793

Not Tested : Create your route like this

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

under your default route

Upvotes: 1

Tallmaris
Tallmaris

Reputation: 7590

If id is a number you could add a route above the other one and define a regex constraint:

routes.MapRoute(
    name: "IdOnlyRoute",
    url: "{id}",
    defaults: new { controller = "Home", action = "Index" },
    constraints: new { id = "^[0-9]+$" }
);

Upvotes: 1

Related Questions