0

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?

4 Answers 4

1

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]+$" }
);
Sign up to request clarification or add additional context in comments.

2 Comments

Nope, it's a string :)
If it is a string with some particular constraints, you can still use the solution above... if it is just a string like anything else then you may be out of luck.
1

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

4 Comments

That just killed all my AJAX calls :)
what's url u r request in ajax?
I have couple of them: /Home/Register/{param}, /Home/Login/{param}, etc
the route i have given you is after the default route also name should be changed
0

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.

Comments

0

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) { /* ... */ }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.