Home > Back-end >  URLs ignore arguments in GET request (ASP.NET)
URLs ignore arguments in GET request (ASP.NET)

Time:09-21

I need to write a Web API for this request:

{apiUrl}/api/sessions/byhour?startTime=2021-06-30T01:00:00&endTime=2021-06-30T03:00:00

So I have this controller and method:

[ApiController]
[Route("/api/sessions/byhour")]
public class LoginStatsByHourController : ControllerBase
{
    [HttpGet, Route("{startTime=0001-01-01T12:00:00}/{endTime=9999-12-31T11:59:59}")]
    public List<SessionEntry> GetSessionEntryByDate(string startTime, string endTime)
    {...}
}

I tested this request:

https://localhost:5001/api/sessions/byhour/2021-07-01T14:00:00/2021-07-01T16:00:00

which essentially equals to:

https://localhost:5001/api/sessions/byhour/2021-07-01T14:00:00/2021-07-01T16:00:00

and everything works fine. But when I try this request:

https://localhost:5001/api/sessions/byhour?startTime=2021-07-01T14:00:00&endTime=2021-07-01T16:00:00

(notice ? and &). And I discovered that these arguments are ignored and the default ones (0001-01-01T12:00:00 and 9999-12-31T11:59:59) are used instead. Why is that so?

CodePudding user response:

Try this :

[HttpGet]
public List<SessionEntry> GetSessionEntryByDate(string startTime, string endTime)
{...}

and call it like this : https://localhost:5001/api/sessions/byhour/GetSessionEntryByDate?startTime=2021-07-01T14:00:00&endTime=2021-07-01T16:00:00

for further reading : checkout this link

CodePudding user response:

It ignores your arguments, because if you want to use a query string you have to remove "{startTime}/{endTime}" and sometimes ( depends on the version) have to add [FromQuery] attribute to each input parameter

[HttpGet]
public List<SessionEntry> GetSessionEntryByDate(string startTime="0001-01-01T12:00:00", 
string endTime="9999-12-31T11:59:59")
    {...}
}

If you still want to use MVC routing , try this

 [HttpGet("{startTime?}/{endTime?}")]
public List<SessionEntry> GetSessionEntryByDate(string startTime="0001-01-01T12:00:00", 
string endTime="9999-12-31T11:59:59")
    {...}
}
  • Related