In ASP.NET Core, How Can Values Be Read From The Querystring Using C#?

In ASP.NET Core, you can read values from the query string by using the HttpContext.Request.Query property. Here’s an example:

  1. Start by injecting the IHttpContextAccessor into your controller or service:
private readonly IHttpContextAccessor _httpContextAccessor;

public YourController(IHttpContextAccessor httpContextAccessor)
{
    _httpContextAccessor = httpContextAccessor;
}
  1. Then, you can access the query string values using the Request.Query property:
public IActionResult YourAction()
{
    string value1 = _httpContextAccessor.HttpContext.Request.Query["key1"];
    string value2 = _httpContextAccessor.HttpContext.Request.Query["key2"];

    // Do something with the values

    return View();
}

In the above code, key1 and key2 are the query string parameter names. You can access their values by indexing the Request.Query object.

Note: Make sure to add the services.AddHttpContextAccessor() line in your Startup.ConfigureServices() method to enable injecting IHttpContextAccessor.

About the Author Rex

I'm a passionate tech blogger with an insatiable love for programming! From my early days tinkering with code, I've delved into web dev, mobile apps, and AI. Sharing insights and tutorials with the world is my joy, connecting me to a global community of like-minded tech enthusiasts. Python holds a special place in my heart, but I embrace all challenges. Constantly learning, I attend tech conferences, contribute to open-source projects, and engage in code review sessions. My ultimate goal is to inspire the next generation of developers and contribute positively to the ever-evolving tech landscape. Let's code together!