[c#] How to read values from the querystring with ASP.NET Core?

I'm building one RESTful API using ASP.NET Core MVC and I want to use querystring parameters to specify filtering and paging on a resource that returns a collection.

In that case, I need to read the values passed in the querystring to filter and select the results to return.

I've already found out that inside the controller Get action accessing HttpContext.Request.Query returns one IQueryCollection.

The problem is that I don't know how it is used to retrieve the values. In truth, I thought the way to do was by using, for example

string page = HttpContext.Request.Query["page"]

The problem is that HttpContext.Request.Query["page"] doesn't return a string, but a StringValues.

Anyway, how does one use the IQueryCollection to actually read the querystring values?

This question is related to c# http asp.net-core query-string .net-core

The answer is


You could use the ToString method on IQueryCollection which will return the desired value if a single page parameter is specified:

string page = HttpContext.Request.Query["page"].ToString();

if there are multiple values like ?page=1&page=2 then the result of the ToString call will be 1,2

But as @mike-g suggested in his answer you would better use model binding and not directly accessing the HttpContext.Request.Query object.


in .net core if you want to access querystring in our view use it like

@Context.Request.Query["yourKey"]

if we are in location where @Context is not avilable we can inject it like

@inject Microsoft.AspNetCore.Http.IHttpContextAccessor HttpContextAccessor
@if (HttpContextAccessor.HttpContext.Request.Query.Keys.Contains("yourKey"))
{
      <text>do something </text>
}

also for cookies

HttpContextAccessor.HttpContext.Request.Cookies["DeniedActions"]

  1. Startup.cs add this service services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
  2. Your view add inject @inject Microsoft.AspNetCore.Http.IHttpContextAccessor HttpContextAccessor
  3. get your value

Code

@inject Microsoft.AspNetCore.Http.IHttpContextAccessor HttpContextAccessor
@{
    var id = HttpContextAccessor.HttpContext.Request.RouteValues["id"];

    if (id != null)
    {
        // parameter exist in your URL 
    }

    string navigation = await Navigation.WebNavigation(activeTab);
}

StringValues is an array of strings. You can get your string value by providing an index, e.g. HttpContext.Request.Query["page"][0].


You can use [FromQuery] to bind a particular model to the querystring:

https://docs.microsoft.com/en-us/aspnet/core/mvc/models/model-binding

e.g.

[HttpGet()]
public IActionResult Get([FromQuery(Name = "page")] string page)
{...}

Maybe it helps. For get query string parameter in view

View:

@inject Microsoft.AspNetCore.Http.IHttpContextAccessor HttpContextAccessor
@{ Context.Request.Query["uid"]}

Startup.cs ConfigureServices :

services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();

ASP.NET Core will automatically bind form values, route values and query strings by name. This means you can simply do this:

[HttpGet()]
public IActionResult Get(int page)
{ ... }

MVC will try to bind request data to the action parameters by name ... below is a list of the data sources in the order that model binding looks through them

  1. Form values: These are form values that go in the HTTP request using the POST method. (including jQuery POST requests).

  2. Route values: The set of route values provided by Routing

  3. Query strings: The query string part of the URI.

Source: Model Binding in ASP.NET Core


FYI, you can also combine the automatic and explicit approaches:

[HttpGet()]
public IActionResult Get(int page
     , [FromQuery(Name = "page-size")] int pageSize)
{ ... }

I have a better solution for this problem,

  • request is a member of abstract class ControllerBase
  • GetSearchParams() is an extension method created in bellow helper class.

var searchparams = await Request.GetSearchParams();

I have created a static class with few extension methods

public static class HttpRequestExtension
{
  public static async Task<SearchParams> GetSearchParams(this HttpRequest request)
        {
            var parameters = await request.TupledParameters();

            try
            {
                for (var i = 0; i < parameters.Count; i++)
                {
                    if (parameters[i].Item1 == "_count" && parameters[i].Item2 == "0")
                    {
                        parameters[i] = new Tuple<string, string>("_summary", "count");
                    }
                }
                var searchCommand = SearchParams.FromUriParamList(parameters);
                return searchCommand;
            }
            catch (FormatException formatException)
            {
                throw new FhirException(formatException.Message, OperationOutcome.IssueType.Invalid, OperationOutcome.IssueSeverity.Fatal, HttpStatusCode.BadRequest);
            }
        }



public static async Task<List<Tuple<string, string>>> TupledParameters(this HttpRequest request)
{
        var list = new List<Tuple<string, string>>();


        var query = request.Query;
        foreach (var pair in query)
        {
            list.Add(new Tuple<string, string>(pair.Key, pair.Value));
        }

        if (!request.HasFormContentType)
        {
            return list;
        }
        var getContent = await request.ReadFormAsync();

        if (getContent == null)
        {
            return list;
        }
        foreach (var key in getContent.Keys)
        {
            if (!getContent.TryGetValue(key, out StringValues values))
            {
                continue;
            }
            foreach (var value in values)
            {
                list.Add(new Tuple<string, string>(key, value));
            }
        }
        return list;
    }
}

in this way you can easily access all your search parameters. I hope this will help many developers :)


Here is a code sample I've used (with a .NET Core view):

@{
    Microsoft.Extensions.Primitives.StringValues queryVal;

    if (Context.Request.Query.TryGetValue("yourKey", out queryVal) &&
        queryVal.FirstOrDefault() == "yourValue")
    {
    }
}

Some of the comments mention this as well, but asp net core does all this work for you.

If you have a query string that matches the name it will be available in the controller.

https://myapi/some-endpoint/123?someQueryString=YayThisWorks

[HttpPost]
[Route("some-endpoint/{someValue}")]
public IActionResult SomeEndpointMethod(int someValue, string someQueryString)
    {
        Debug.WriteLine(someValue);
        Debug.WriteLine(someQueryString);
        return Ok();
    }

Ouputs:

123

YayThisWorks


IQueryCollection has a TryGetValue() on it that returns a value with the given key. So, if you had a query parameter called someInt, you could use it like so:

var queryString = httpContext.Request.Query;
StringValues someInt;
queryString.TryGetValue("someInt", out someInt);
var daRealInt = int.Parse(someInt);

Notice that unless you have multiple parameters of the same name, the StringValues type is not an issue.


You can just create an object like this:

public class SomeQuery
{
    public string SomeParameter { get; set; }
    public int? SomeParameter2 { get; set; }
}

And then in controller just make something like that:

[HttpGet]
public IActionResult FindSomething([FromQuery] SomeQuery query)
{
    // Your implementation goes here..
}

Even better, you can create API model from:

[HttpGet]
public IActionResult GetSomething([FromRoute] int someId, [FromQuery] SomeQuery query)

to:

[HttpGet]
public IActionResult GetSomething(ApiModel model)

public class ApiModel
{
    [FromRoute]
    public int SomeId { get; set; }
    [FromQuery]
    public string SomeParameter { get; set; }
    [FromQuery]
    public int? SomeParameter2 { get; set; }
}

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to http

Access blocked by CORS policy: Response to preflight request doesn't pass access control check Axios Delete request with body and headers? Read response headers from API response - Angular 5 + TypeScript Android 8: Cleartext HTTP traffic not permitted Angular 4 HttpClient Query Parameters Load json from local file with http.get() in angular 2 Angular 2: How to access an HTTP response body? What is HTTP "Host" header? Golang read request body Angular 2 - Checking for server errors from subscribe

Examples related to asp.net-core

dotnet ef not found in .NET Core 3 How to use Bootstrap 4 in ASP.NET Core ASP.NET Core - Swashbuckle not creating swagger.json file Getting value from appsettings.json in .net core .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Automatically set appsettings.json for dev and release environments in asp.net core? Get ConnectionString from appsettings.json instead of being hardcoded in .NET Core 2.0 App Unable to create migrations after upgrading to ASP.NET Core 2.0 EF Core add-migration Build Failed ASP.NET Core form POST results in a HTTP 415 Unsupported Media Type response

Examples related to query-string

How can I get (query string) parameters from the URL in Next.js? How to read values from the querystring with ASP.NET Core? What is the difference between URL parameters and query strings? How to get URL parameter using jQuery or plain JavaScript? How to access the GET parameters after "?" in Express? node.js http 'get' request with query string parameters Escaping ampersand in URL In Go's http package, how do I get the query string on a POST request? Append values to query string Node.js: Difference between req.query[] and req.params

Examples related to .net-core

dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Assets file project.assets.json not found. Run a NuGet package restore Is ConfigurationManager.AppSettings available in .NET Core 2.0? How to update record using Entity Framework Core? Using app.config in .Net Core EF Core add-migration Build Failed Build .NET Core console application to output an EXE What is the difference between .NET Core and .NET Standard Class Library project types? Where is NuGet.Config file located in Visual Studio project?