ASP dot net core

165 Views Asked by At

I'd like to know how to specify routes in dot net core. For example, I have a get method, which gets 1 argument(id), and returns user. This method is available through this link (api/user/1). So, the question is how to make a method to this link -"api/user/1/profile" so that it will get ID and returns something relevant to this ID. Is it necessary to make 2 get methods, or just separate them and specify routes?

2

There are 2 best solutions below

0
On

If you haven't changed the default route from:

app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}/{id?}");
});

You could create a User controller with something like:

public async Task<IActionResult> Profile(int? id)
{
    if (id == null)
    {
        // Get the id
    }

    var profile = await _context.Profile
        .SingleOrDefaultAsync(m => m.Id == id);
    if (profile == null)
    {
        return NotFound();
    }

    return View(profile);
}

Then it would be mapped to "/User/Profile/{id}"

Obviously you can get the data for the profile however you wish, I just used an EFCore example.

0
On

Using attribute based routing, it can be done like this.

[HttpGet("{id:int}")]
public async Task<IActionResult> GetUserById(int id) {}

[HttpGet("{id:int}/profile")]
public async Task<IActionResult> GetUserProfileById(int id) {}

More information on routing can be found at this link.

https://docs.asp.net/en/latest/fundamentals/routing.html