0

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%3A00%3A00-04%3A00&end=2022-12-11T00%3A00%3A00-05%3A00

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

1
  • 1
    the parameters which have not been added to the route template will be available from the querystring. So, your route can be defined as [HttpGet("{id}")]. This can then be called with /api/roomEvents/1a?start=...&end=... Commented Nov 15, 2022 at 15:29

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.