Search code examples
c#asp.net-coreasp.net-core-webapiasp.net-core-routing

ASP.NET 2.0 Web API with 2 parameters problem


I wrote the following code to get a web api that accepts two parameters:

[Route("api/[controller]")]
[ApiController]
public class EventsController : ControllerBase
{
    // GET: api/events/5
    [Route("api/[controller]/{deviceId}/{action}")]
    [HttpGet("{deviceId}/{action}")]
    public IEnumerable<CosmosDBEvents> Get(string deviceId,string action)
    {
        try
        {
            return null;
        }
        catch(Exception ex)
        {
            throw (ex);
        }
    }
}

I try to invoke it with the following url:

https://localhost:44340/api/events/abcde/indice

but it does not work. The error is 404 , Page not found.

I also changed the code as shown below but nothing changes :

[Route("~/api/events/{deviceId}/{action}")]
[HttpGet("{deviceId}/{action}")]
public IEnumerable<CosmosDBEvents> Get(string deviceId,string action)
{
    try
    {
        return null;
    }
    catch(Exception ex)
    {
        throw (ex);
    }
}

What am I doing wrong?


Solution

  • When using ASP.NET Core routing, there are a few Reserved routing names. Here's the list:

    • action
    • area
    • controller
    • handler
    • page

    As you can see, action is on the list, which means you cannot use it for your own purposes. If you change action to something else that's not on the list, it will work:

    [Route("api/[controller]")]
    [ApiController]
    public class EventsController : ControllerBase
    {
        [HttpGet("{deviceId}/{deviceAction}")]
        public IEnumerable<CosmosDBEvents> Get(string deviceId, string deviceAction)
        {
            // ...
        }
    }
    

    Note that I've also removed the [Route(...)] attribute from Get, which was redundant due to your use of the [HttpGet(...)] attribute that also specifies the route.