I had asked this question on Regex parsing with multiple named groups. This is the original problem that motivated that question and is an orthogonal problem.
In .net 7, using the minimal apis is there a way to map multiple key-value pairs that appear in the url query parameters? The documentation in the previous link gives examples of binding a single parameter to the url fragment or slug. How do we map multiple key-value pairs?
The asp.net core documentation provides the following example:
app.MapGet("/{id}", (int id,
int page,
[FromHeader(Name = "X-CUSTOM-HEADER")] string customHeader,
Service service) => { });
where
id
is mapped to the path parameter,page
is mapped to the query parameter,customHeader
is mapped to a header field,service
is provided by dependency injectionMy Example URL is: /o/post?id=123&filter=xyz
Does .net 7 asp.net core provide a way to map the id
and filter
parameters to a handler automatically or should I use
app.MapGet("/o/{*rest}", (string rest) => $"Routing to {rest}");
and handle the parsing myself?
I am thinking there should be a simpler way than handling the parsing myself. Is there one?
After reading your comment, yes this is easily possible with minimal APIs. What you have to do is to pass the HttpRequest and access the query of that request.
I would do something like this.
app.MapGet("/{type}", (string type,
HttpRequest request) =>
{
return new { Type = type, queryParams = request.Query};
}); ;
if you now call your endpoint like this /comment?userID=21546&commentID=76165
you will get this result:
{
"type": "comment",
"queryParams": [
{
"key": "userID",
"value": [
"21546"
]
},
{
"key": "commentID",
"value": [
"76165"
]
}
]
}
If you call this URL /post?postID=76165
you will get this response. As you can see only the sent query parameters are available.
{
"type": "post",
"queryParams": [
{
"key": "postID",
"value": [
"76165"
]
}
]
}
You can then build a switch case based on the type string and do whatever logic you need. Hope this puts you in the right direction.