Search code examples
webapi.net-8.0

routing in web api use slash instead of questionmark


I have controller called Player

I want to access each player like this:

GET /msdo/v1/player/5

however currently it can only be done like this

GET /msdo/v1/Player?id=1

I've been trying to change quite a few things.

the code as it is right now is pretty standard:

[HttpGet(Name = "{id}")]
public string Get(int id)
{
    return "value";
}

I've tried with changeing {id} into {*id} I've tried with changeing {id} into /{id} I've tried a few other things where I started to change default route however that made it even worse by making a 500 error. so here I am looking for an answer to something that seemed so simple before I started and have been quite a hurdle to get over.

EDIT 1: added more code from my controller

[Route("/msdo/v1/[controller]")]
[ApiController]
public class PlayerController : ControllerBase
{

    // GET /msdo/v1/player/5

    [HttpGet(Name = "{id}")]
    public string Get(int id)
    {
        return "value";
    }
 }

Edit 2: Found a Possible solution. I don't know if it is a good one so I'm going to leave this question open to see if someone comes up with a better solution.

However here is my solution to the question:

 [HttpGet("/msdo/v1/[controller]/{id}", Name = "{id}")]
 public string Get(int id)
 {
      return "value";
 }

Solution

  • Try this adding route attribute [Route("{id}")] above your method. And insted of [HttpGet(Name = "{id}")] just leave [HttpGet].