How to get values from the querystring in ASP.NET Core?

Dung Do Tien Aug 18 2020 907

I am building an application using Asp.net Core MVC 3.1. I have created a middleware to filter login and I want to get username param from URL. I use code as below:

string username = HttpContext.Request.Query["username"];

The problem is that HttpContext.Request.Query["username"] doesn't return a string.

So how to get values from the query string in ASP.NET Core? Thanks for any suggestions!!!

Have 1 answer(s) found.
  • S

    Sandeep Kumar Aug 18 2020

    You need to cast it to string. You can replace your code to as below:

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

    You can use this way inside a html page, middleware, logic business layer.

    But if get query string inside an action of a controller you can get it throught parameter, as below :

    [HttpGet]
    public IActionResult Login(string username)
    {
      // Variable username will hold value of query string from url
       return View();
    } 

    If you want to access querystring in view cshtm, you can use code below:

    @{
      var username  = Context.Request.Query["username"].ToString();
    } 

    I hope this answer is helpful for you.

Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close