I want to read the values of a request in C# sent using JavaScript's fetch method with Query String Parameters. I want to check the request in C# to see how it is received using HttpContext class.
-
This is a very vague question. The fact you have access to HttpContext means you're using a controller or minimal API. In that case the query parameters can be bound to action parameters easily. In most cases it's as simple as using an action parameter with the same name as the query parameter. You can fine tune this with parameter attributes.Panagiotis Kanavos– Panagiotis Kanavos2023-09-07 13:24:56 +00:00Commented Sep 7, 2023 at 13:24
-
I need to debug the result I have got from a request in a complex application. model binding and appropriate attributes are used [FromQuery], [FromForm], etc.Stepan Michalek– Stepan Michalek2023-09-07 13:59:27 +00:00Commented Sep 7, 2023 at 13:59
Add a comment
|
1 Answer
You can read the whole query string with: HttpContext.Request.QueryString.
To read the first value of query parameter "foo" use: HttpContext.Request.Query["foo"][0].
To check if the key is contained in HttpContext you can use: HttpContext.Request.Query.Keys.Contains("foo").
5 Comments
Peter Csala
The presented code can throw exception if "foo" is not present in the query string. Be sure to check the presence of the key before you try to access the value.
Panagiotis Kanavos
What's the point of this question? Not only is
QueryString well documented, there are a lot of similar questions. Never mind that the query parameters may already be available as action parameters. If you have access to HttpContext, you're using either a Controller or a minimal API, both of which bind the query string to action parametersPanagiotis Kanavos
Is the real question how to access array values? There are a lot of duplicates too, and first you need to find a way to send the array. There's no standard for this. As this possibly duplicate question shows ASP.NET Core will bind multiple values with the same name to an array parameter, eg
?values=this&values=that maps to string[] valuesStepan Michalek
I wanted to know how to check the request's received query parameters using HttpContext. The closest to this question I was able to find was this. But it is not a duplicate, right?
Panagiotis Kanavos
Actually it is an exact duplicate. The second answer shows
HttpContext.Request.Query["page"]. Your code is trying to access an array value. That's answered in Pass Array into ASP.NET Core Route Query String