Home > Enterprise >  c# .net core api controller mixing route parameters and query parameters
c# .net core api controller mixing route parameters and query parameters

Time:11-16

I have a url (that I can't really modify) that has id as part of the route and then a start date and end date as query parameters.

I'm not sure how to mix route parameters and query parameters and bind them.

https://localhost:7285/api/roomEvents/1a?start=2022-10-30T00:00:00-04:00&end=2022-12-11T00:00:00-05:00

I'm struggling to bind the id, start, and end strings in my c# web api controller.

I've tried

 public class RoomEvents : BaseApiController
    {
        [AllowAnonymous]
        [HttpGet("{id}?start={start}&end={end}")]
        public async Task<ActionResult> GetRoomEvents(string id, string start, string end)
        {
           return HandleResult(await Mediator.Send(new EventsByRoom.Query { Id = id, Start = start, End = end }));
        }
         
    }

but I get

System.ArgumentException HResult=0x80070057 Message=The literal section '?start=' is invalid. Literal sections cannot contain the '?' character. (Parameter 'routeTemplate')
Source=Microsoft.AspNetCore.Routing

CodePudding user response:

You need to change your [HttpGet] path and the method parameters to this

[HttpGet("{id}")]
public async Task<ActionResult> GetRoomEvents(
    string id,
    [FromQuery] string start,
    [FromQuery] string end)
    ...

The first parameter, id will be bound to the {id} portion of the path. for the latter two parameters you are explicitly telling ASP.NET that you want to bind to query parameters with the names start and end (using [FromQuery]).

You can also specify [FromRoute] for id if you want to be explicit, but that's the default.

  • Related