asp.net core route handle id after domain

73 views Asked by At

How can I handle this in the ASP.NET Core route http://example.com/id?

Basically, I need to be able to format some URL with some kind of id right after the domain (please notice this is not /Home/Index).

So assuming I want to display an image with id=1 when you visit the url: http://example.com/1 or http://example.com?id=1 where can I put my logic? How can I handle this route?

2

There are 2 answers

1
Stephen Vernyi On BEST ANSWER

This is basic routing, and the docs answer for you how to do this.

To strictly handle http://example.com/{id}, you need to define a default controller (typically HomeController), and define a route that matches the id.
Inside HomeController would be an action that looks something like

[HttpGet("{id}")]
public void GetImage(string id) {
    ...
}
0
user3492281 On

For MVC5 you can add a new route for example and make it before the default route

routes.MapRoute(
    name: "custom",
    url: "{Id}",
    defaults: new { controller = "controller-name", action = "action-name"}
);