Home > Back-end >  How does HttpRequest.Query[] in .net core works?
How does HttpRequest.Query[] in .net core works?

Time:12-15


How does the below statement work?

I tried to see in Microsoft documentation, but couldn't find much information

Link to Microsoft documentation

var queryString = this.Request.Query[SomeConstant.QueryString];

CodePudding user response:

Lets assume you hit any of your endpoint with

/someendpoint?foo=bar&name=Vamsi

You can now get the whole QueryCollection with:

var queries = this.Request.Query;

If you want to retrieve a specific value by its key, you can use that:

var foo = this.Request.Query["foo"]   //value: bar
var name = this.Request.Query["name"] //value: Vamsi

So to answer your question: Query[SomeConstant.QueryString] is accessing the QueryCollection of the current request by accessing a specific key, that is stored in a variable called SomeContant.QueryString

CodePudding user response:

The Query object here is an IQueryCollection

The IQueryCollection Implements both :

IEnumerable<KeyValuePair<String,StringValues>>
IEnumerable

suppose we have the following Url : http://localhost/home/index?code=A000

The key value pair you can see it as a dictionnary, we have a key that represent the query string parameter name (ex: code) and we had a value (ex: A000)

In order to retreive the code from the url, you have to search in that list and find this name. To do that, you call Query["code"]

In your case SomeConstant.QueryString is a constant defined somewhere in your projet in a class with name SomeConstant and a const with name QueryString and the value of this const is "code".

public Class SomeConsant{
    public const string SomeConstant = "code";
}
  • Related