Learn ASP.NET MVC, ASP.NET Core, and Design Patterns through our online training programs. Courses conducted by Bipin Joshi on weekends. Read more details here.

Form, Query String and HttpContext in ASP.NET Core 1.0

ASP.NET Core is a modern web development framework. Features such as model binding make your life easy by mapping form field values with model properties. So, accessing form and query string values manually might not be needed so often. However, at times you may need to read the form collection and query string values manually. The same can be said about Items collection of HttpContent. This article discusses how the form collection, query string values and Items collection can be accessed in ASP.NET Core. You will also learn how HttpContext can be accessed inside classes other than the controller.

To illustrate what we just mentioned you will develop a simple web application as shown below:

As you can see the page consists of a simple form that allows you to enter first name and last name. Upon click the Submit button a welcome message is displayed below.

Reading Form collection

To understand how the form collection can be accessed let's POST the above form to an action :

<h1>Enter your name :</h1>

<form asp-action="ProcessForm"
      asp-controller="Home" method="post">
    <label for="firstName">First Name :</label>
    <input type="text" name="firstname" />
    <label for="lastName">Last Name :</label>
    <input type="text" name="lastname" />
    <input type="submit" value="Submit" />
</form>

<h4>@ViewBag.Message</h4>

The above form consists of two text input fields and a submit button. The form is POSTed to the ProcessForm() action of the HomeController. The ProcessForm() action is shown below:

public IActionResult GetForm()
{
 string firstName = HttpContext.Request.Form["firstname"];
 string lastName = HttpContext.Request.Form["lastname"];
 ViewBag.Message = $"Welcome {firstName} {lastName}!";
 return View("Index");
}

Since the form is submitted to the server using a POST request, its values need to be accessed using the Form collection of the Request object. This is quite similar to ASP.NET Web Forms or ASP.NET MVC. The form collection is a dictionary that can be accessed using a key-value notation. The above code uses firstname and lastname keys to read the respective values. Notice that these keys are same as the name attributes of the text input fields. The code then forms a welcome message and stores it in ViewBag's Message property.

If you run the application you will get results as shown earlier.

Reading query string values

Now, change the method of the <form> element to GET and change the asp-action to ProcessQueryString.

<form asp-action="ProcessQueryString"
      asp-controller="Home" method="get">
...
</form>

Since the form is now being submitted through GET request, the values will be sent through query string. To access these values on the server you need to write ProcessQueryString() action as follows :

public IActionResult ProcessQueryString()
{
 string firstName = HttpContext.Request.Query["firstname"];
 string lastName = HttpContext.Request.Query["lastname"];
 ViewBag.Message = $"Welcome {firstName} {lastName}!";
 return View("Index");
}

In this case you use Query collection (not QueryString ptoperty!). As before Query collection is accessed by specifying a key. A welcome message is formed as before. You can access y string values sent via plain hyperlinks (rather than form submission) in the same manner.

Storing and retrieving items in the Items collection of HttpContext

The Items collection of the HttpContext is used to store data that is accessible within the current request. Once the current request ends the Items collection is emptied. Let's say you wish to store arbitrary number of key-value pairs in Items collection so that they can be accessed in other classes. You can store data in Items collection like this :

 public IActionResult ProcessForm()
{
    HttpContext.Items["firstname"] = 
              HttpContext.Request.Form["firstname"];
    HttpContext.Items["lastname"] = 
              HttpContext.Request.Form["lastname"];
    ViewBag.Message = helper.DoWork();
    return View("Index");
}

The above code shows the modified version of ProcessForm(). The modified ProcessForm() retrieves firstname and lastname from Form collection and stores them in the Items collection of HttpContext. The code then invokes DoWork() method on a helper object. The helper object (discussed later) is supposed to read the Items collection and return the welcome message.

This means inside the helper object you need to access the HttpContext. The HttpContext is available readily in the controller classes but if you wish to access it inside a class (let's call it a helper class for simplicity) you need to do a few things. Firstly, you need to register the HttpContextAccessor (Microsoft.AspNetCore.Http namespace) and your helper class as shown below:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddSingleton
        <IHttpContextAccessor,HttpContextAccessor>();
    services.AddScoped<MyHelperClass>();
}

 Here, you registered HttpContextAccessor as a singleton service. You also registered MyHelperClass as a scoped service. Once registered you can inject the HttpContextAccessor in the MyHelperClass. As the name implies the HttpContextAccessor allows you to access the web application's HttpContext object. The MyHelperClass is shown below:

public class MyHelperClass
{
    IHttpContextAccessor contextAccessor;

    public MyHelperClass(IHttpContextAccessor 
                          contextAccessor)
    {
        this.contextAccessor = contextAccessor;
    }

    public string DoWork()
    {
        string firstName = contextAccessor.
                  HttpContext.Items["firstname"].ToString();
        string lastName = contextAccessor.
                  HttpContext.Items["lastname"].ToString();
        return $"Welcome {firstName} {lastName}!";
    }
}

Notice the MyHelperClass class carefully. It declares a private variable of type IHttpContextAccessor. The IHttpContextAccessor object is injected in the constructor and is stored in the variable. The DoWork() method then retrieves the firstname and lastname items using the HttpContext property of IHttpContextAccessor. This way the web application's HttpContext can be accessed inside any class.

If you run the application you should see the welcome message displayed as expected.

That's it for now! Keep coding!!




Bipin Joshi is a software consultant, trainer, author and a yogi having 21+ years of experience in software development. He conducts online courses in ASP.NET MVC / Core, jQuery, AngularJS, and Design Patterns. He is a published author and has authored or co-authored books for Apress and Wrox press. Having embraced Yoga way of life he also teaches Ajapa Meditation to interested individuals. To know more about him click here.

Get connected : Twitter  Facebook  Google+  LinkedIn

Posted On : 27 Jun 2016



Tags : ASP.NET ASP.NET Core C#