Reading Request Body in ASP.NET MVC

watch_later 08 May, 2021

In this article, I will explain how to read the JSON POST request body in ASP.NET MVC. Here I'll also explain different kinds of ways to read the request body in the action method of the MVC controller. Here I'll also show how you can pass data into the request body using AJAX call.

Reading Request Body in ASP.NET MVC

In my previous article, I explained, How to Bind WebGrid in ASP.NET MVC and How to Create REST API with ASP.NET Core 5.0 And Entity Framework Core and Export Data to CSV File Using ASP.NET MVC and Upload and Read Excel File in WEB API using C# as well as Angular 11 CRUD Application using Web API With Material Design that you might like to read.

Requirement 

  1. Explain how to pass data into the request body using postman as well as AJAX calls.
  2. Describe multiple ways to read JSON POST request body in MVC.

Implementation

So, let's start with a simple example of students, Assume that we have one JSON string that contains information of students like roll number, name, branch, university and etc.

So, First I'll show you how to pass these JSON strings into the request body using the AJAX call and then I will show you how you can read that JSON string from the request body.

<script type="text/javascript">
    $(document).ready(function () {
        var _requestURL = "Home/Index";
        var _jsonData = {
            "RollNo""017",
            "EnrollmentNo""14SOECE13017",
            "Name""Nikunj Satasiya",
            "Branch""Computer Engineering",
            "University""RK University"
        };
 
        $.ajax({
            type: "POST",
            url: _requestURL,
            data: _jsonData,
            dataType: 'json',
            async: false,
            success: function (result) {
                //...
            },
            error: function (error) {
                //...
            }
        });
    });
</script>

Explanation

As you can see in the code, at the top we have declared a variable _requestURL that contains the URL and execute the Index action method of the HomeController, as in this example we have used the Index action method of the Home controller for reading the data from request body, here you can change the URL based on your controller and action method.

Then we have declared another variable, _jsonData, and assign the above JSON string into this variable.

Finally, we have created an AJAX call and create a POST method as you can see in the type property it is POST, then we have to assign _requestURL to URL and _jsonData as data and then selected dataType as JSON, and it's all done, other properties are optional that you can customize based on your need or requirement as here we have set async as false for the asynchronous call.

Create Request Using Postman

If you want to test the same without any AJAX call, you can try with postman as I show below.

Postman

Here, I have selected the request method as POST, pass URL that will execute our Index action method from HomeControllar. Then choose the body section and selected raw data >> JSON

Now, Under the Input area of body selection writes your JSON object as shown in the screenshot.

Read Request Body from Action Method of MVC controller

Now, let's learn how to read the data from the request body, So Here I am going to explain two different methods for the same.

From Parameter

This is a normal approach to deal with the same, and you can use this way while you have a properly fixed JSON object in the request body with the same properties as per your model class. Suppose, assume that you have a model class for students as shown below.

public class Student
   {
       public int Student_Id { getset; }
       public int RollNo { getset; }
       public string EnrollmentNo { getset; }
       public string Name { getset; }
       public string Branch { getset; }
       public string University { getset; }
   }

You can directly read the data from the request body by adding these models as a parameter into your action method as shown in the code below. It will automatically match the properties of the model and your JSON object and set its appropriate value available in the JSON object to the model properties.

public ActionResult Index(Student model)
{
    //...
}

From Request Object

While you didn't have any fixed fields, properties, or datatype at the same time you can use this approach.

public ActionResult Index()
{
    Stream req = Request.InputStream;
    req.Seek(0, System.IO.SeekOrigin.Begin);
    string json = new StreamReader(req).ReadToEnd();
    //...
}

As you can see in the code above here, we have used Request.InputStream and Request.InputStream allows you to access the raw request data. We have stored the result of the Request.InputStream to the stream variable req. Then we retrieved the new position within the current stream req. Finally by creating the object of StreamReader read all the stream and stored the result into a final variable called json.

Summary

In this article, we learned how to pass input data into the request body as well as a way to read the request body from the action method of the MVC controller. 

Codingvila provides articles and blogs on web and software development for beginners as well as free Academic projects for final year students in Asp.Net, MVC, C#, Vb.Net, SQL Server, Angular Js, Android, PHP, Java, Python, Desktop Software Application and etc.

Thank you for your valuable time, to read this article, If you like this article, please share this article and post your valuable comments.

Once, you post your comment, we will review your posted comment and publish it. It may take a time around 24 business working hours.

If you have any questions regarding this article/blog you can contact us on info.codingvila@gmail.com

sentiment_satisfied Emoticon