Fetching Data Using Web API In React

In this article, I`m going to display (Fetching) data using ASP.net web API in React JS. For this we require two applications which are 1. ASP.NET MVC + React.MVC (Nuget Package). 2. ASP.NET WEB API.

In this article, I'm going to display (Fetching) data using ASP.net web API in React JS. For this we require two applications which are 1. ASP.NET MVC + React.MVC  (Nuget Package). 2. ASP.NET WEB API.

  1. ASP.NET MVC + React.MVC (Nuget Package): You can follow my previous article steps to creating ASP.NET MVC project and install React.MVC and other required nuget packages.

  1. ASP.NET WEB API: I am going to create ASP.NET WEB API project using Visual Studio. In this sample Web API project I`ll create a web API end point to get sample data and return it in json format. And this sample API will call from React JS to populate data and display on view.

Let’s start to create ASP.NET Web API Project

Open Visual Studio from the start menu or taskbar icon

After that click on - File => New => Project

  1. When clicking on the Project open a "New Project” popup, and from there we can select a project and enter the web API application name and select folder location.
  2. Open a "New Project" popup and select Template => Visual C# => Web => ASP.NET Web Application (.NET Framework)

    React

  3. Open popup (dialog) - New ASP.NET Application – WebAPI

    React

In this dialog popup, we select "Empty" project template as in the below list of project templates. And in the below project templates list select "Add folders and core references for:” e.g. Web Form, MVC & Web API etc. We'll select Web API for now. And click on the OK button.

  1. Now we are going create a web API controller by right clicking on Controller folder and add a “Web API 2 Controller” as per below screenshot

    React

Select “Web API Controller” from option and click on “Add” button. In the second step, add controller name e.g. “ProductsController”. In this controller we can create method; e.g. Get list, single records etc. as per requirement. Now we are creating a simple method to return Products list and will use it in React to display records (data).

  1. After that I`m creating a Model; e.g. ProductModel, inside the “Models” folder. In this model I am creating properties related to product.

    React

    Model class looks like => Models => ProductModel.CS
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Linq;  
    4. using System.Web;  
    5.   
    6. namespace WebAPI.Models  
    7. {  
    8.             public class ProductModel  
    9.             {  
    10.                 public int ProductId { get; set; }  
    11.                 public string ProductName { get; set; }  
    12.                 public string ProductCategory { get; set; }  
    13.                 public decimal ProductPrice { get; set; }  
    14.         }  
    15. }  
  1. Now I`m creating a sample product list inside the controller for now with the other two methods to get Products list and single product by product id.

    Controller => ProductsController.cs
    1. using System.Collections.Generic;  
    2. using System.Linq;  
    3. using System.Web.Http;  
    4. using WebAPI.Models;  
    5.   
    6. namespace WebAPI.Controllers  
    7. {  
    8.         public class ProductsController : ApiController  
    9.             {  
    10.                 ProductModel[] products = new ProductModel[]  
    11.                 {  
    12. new ProductModel { ProductId = 1, ProductName = "Tomato Soup", ProductCategory = "Groceries", ProductPrice = 1 },  
    13.   
    14. new ProductModel { ProductId = 2, ProductName = "Yo-yo",     ProductCategory = "Toys", ProductPrice = 3.75M },  
    15.   
    16. new ProductModel { ProductId = 3, ProductName = "Hammer",     ProductCategory = "Hardware", ProductPrice = 16.99M },  
    17.   
    18. new ProductModel { ProductId = 4, ProductName = "Sugar", ProductCategory = "Groceries", ProductPrice = 10 },  
    19.   
    20. new ProductModel { ProductId = 5, ProductName = "Chhota-Bheem", ProductCategory = "Toys", ProductPrice = 15 },  
    21.   
    22. new ProductModel { ProductId = 6, ProductName = "Printer", ProductCategory = "Hardware", ProductPrice = 120 }  
    23.                 };  
    24.   
    25.             // GET: api/Products  
    26.             public List<ProductModel> Get()  
    27.             {  
    28.                     return products.ToList();  
    29.             }  
    30.           
    31.             public IHttpActionResult Get(int id)  
    32.             {  
    33.                 var product = products.Where(x => x.ProductId == id).ToList();  
    34.                     if (product == null)  
    35.                  {  
    36.                         return NotFound();  
    37.                     }  
    38.                     return Ok(product);  
    39.             }  
    40.             }  
    41. }  
    Web API endpoint is: http://localhost:51260/api/products  it will return a products list in XML format. Now I am going to set JSON as a return format.
  • App_Start Folder => CS
    1. using System.Net.Http.Headers;  
    2. using System.Web.Http;  
    3.   
    4. namespace WebAPI  
    5. {  
    6.     public static class WebApiConfig  
    7.     {  
    8.         public static void Register(HttpConfiguration config)  
    9.         {  
    10.            // Web API configuration and services  
    11.   
    12.             // Web API routes  
    13.             config.MapHttpAttributeRoutes();  
    14.   
    15.             config.Routes.MapHttpRoute(  
    16.                 name: "DefaultApi",  
    17.                 routeTemplate: "api/{controller}/{id}",  
    18.                 defaults: new { id = RouteParameter.Optional }  
    19.             );  
    20.   
    21.             //Set Json Formatter  
    22.             config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));  
    23.         }  
    24.     }  
    25. }  
    React

    JSON Result
    1. [{"ProductId":1,"ProductName":"Tomato Soup","ProductCategory":"Groceries","ProductPrice":1.0},{"ProductId":2,"ProductName":"Yo-yo","ProductCategory":"Toys","ProductPrice":3.75},{"ProductId":3,"ProductName":"Hammer","ProductCategory":"Hardware","ProductPrice":16.99},{"ProductId":4,"ProductName":"Sugar","ProductCategory":"Groceries","ProductPrice":10.0},{"ProductId":5,"ProductName":"Chhota-Bheem","ProductCategory":"Toys","ProductPrice":15.0},{"ProductId":6,"ProductName":"Printer","ProductCategory":"Hardware","ProductPrice":120.0}]  
    Let's start to consume web api in React JS application
  1. First of all follow all steps as per the previous article

ASP.NET MVC + React.MVC (Nuget Package): You can follow my previous article steps to create ASP.NET MVC project and install React.MVC and other required nuget packages.

  1. Now when creating .JSX React Component, we need to create a component for Product (.jsx) by right clicking on container folder script => react folder => select a file from new items dialog popup and click on Add button. The file is called : "ProductList.jsx"

    Select Web (MVC.ReactApp) => JSX File, and enter file name "ProductList.jsx". Then, click on "Add" button

    React
  1. Now we are going to CDN of “AXIOS” to perform HTTP request

    AXIOS
    Axios is a Promise-based HTTP client for JavaScript which can be used in your front-end application and in your Node.js backend.

Use CDN and add it on Layout.cshtml page:

  1. <script src="https://unpkg.com/axios/dist/axios.min.js"></script>  

Layout.cshtml

  1. <!--All Required REACTJS Lib-->  
  2. <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.2/react.js"></script>  
  3. <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.2/react-dom.js"></script>  
  4.   
  5. <script src="https://cdnjs.cloudflare.com/ajax/libs/remarkable/1.7.1/remarkable.min.js"></script>  
  6. <script src="https://cdnjs.cloudflare.com/ajax/libs/prop-types/15.6.0/prop-types.js"></script>  
  7.   
  8. ;script src="https://unpkg.com/axios/dist/axios.min.js"></script>  

Error 

No 'Access-Control-Allow-Origin' header is present on the requested resource.

For this error we need to add some code in web.config of web API project

  1. <system.webServer>      
  2.    <httpProtocol>  
  3.        <customHeaders>  
  4.          <add name="Access-Control-Allow-Origin" value="*" />  
  5.          <add name="Access-Control-Allow-Headers" value="Content-Type" />  
  6.          <add name="Access-Control-Allow-Methods" value="GET,POST,PUT,DELETE,OPTIONS" />  
  7.         <add name="Access-Control-Allow-Credentials" value="true" />  
  8.        </customHeaders>  
  9.      </httpProtocol>  
  10.   </system.webServer>  

Note
Now we can enable access web API from front end inside React .jsx file.

Use the new modern ES6 pattern to create " ProductList" component likes below:

Scripts => react => ProductList.jsx

  1. class ProductsList extends React.Component {  
  2.     constructor() {  
  3.         super();  
  4.         this.state = {  
  5.             ProductData: []  
  6.         }  
  7.     }  
  8.   
  9.     componentDidMount() {  
  10.         axios.get("http://localhost:51260/api/products").then(response => {  
  11.             //console.log(response.data);  
  12.             this.setState({  
  13.                 ProductData: response.data  
  14.             });  
  15.         });  
  16.     }  
  17.   
  18.     render() {  
  19.   
  20.         return (  
  21.             <section>  
  22.                 <h1>Products List</h1>  
  23.                 <div>  
  24.                     <table>  
  25.                         <thead><tr><th>Product Id</th><th>Product Name</th><th>Product Category</th><th>Product Price</th></tr></thead>  
  26.                         <tbody>  
  27.                             {  
  28.                                 this.state.ProductData.map((p, index) => {  
  29.                                     return <tr key={index}><td>{p.ProductId}</td><td> {p.ProductName}</td><td>{p.ProductCategory}</td><td>{p.ProductPrice}</td></tr>;  
  30.                                 })  
  31.                             }  
  32.                         </tbody>  
  33.                     </table>  
  34.                 </div>  
  35.   
  36.   
  37.             </section>  
  38.         )  
  39.     }  
  40. }  
  41.   
  42. ReactDOM.render(  
  43.     <ProductsList />,  
  44.     document.getElementById('myContainer'));   

.NET Bundling and Minification

We need to add ProductList.jsx file to create a new bundles.add() inside the bundleConfig file to compile our JSX to JavaScript and then minify it.

React.Web.Mvc4 supports the use of Microsoft's ASP.NET Bundling and Minification library to transform JavaScript via Babel and minify it along with all your other JavaScript. Simply create a BabelBundle containing any number of JSX or regular JavaScript files: (source: react)

App_Start => BundleConfig.cs

  1. using System.Web;  
  2. using System.Web.Optimization;  
  3. using System.Web.Optimization.React;  
  4.   
  5. namespace FirstReactApp  
  6. {  
  7.     public class BundleConfig  
  8.     {  
  9.         // For more information on bundling, visit https://go.microsoft.com/fwlink/?LinkId=301862  
  10.         public static void RegisterBundles(BundleCollection bundles)  
  11.         {  
  12.             
  13.             bundles.Add(new BabelBundle("~/bundles/main").Include(  
  14.                      "~/Scripts/react/ProductList.jsx"));  
  15.         }  
  16.     }  
  17. }  

Add main bundle as per mentioned above in to _Layout.cshtml page

  1. @Scripts.Render("~/bundles/main")  

Now Run the Web API project and after that run the ASP.NET MVC + React Application.

And finally run both applications and display expected result from http get request with ASP.NET MVC + React JS + AXIOS.

React