Restful Web Services Tutorial with ASP.NET MVC

Restful Web Services Tutorial – From my previous Article on how to Create Web API in ASP.NET. We have created an API method that will return Hello + the name input by the user. Now in this article let’s consume that API using a client Application.

Let’s start: – Restful Web Services Tutorial

1. Create a new ASP.NET MVC Web Application Project.

Create New Project

2. I assume you have already created a project. Now we will use again the default Controller of MVC which is HomeController. Open HomeController by navigating to Solution explorer->Controller folder and open HomeController.

HomeController

3. From your Index function inside your HomeController, lets create additional code that will connect as to the API we created from the previous blogs ASP.NET WEB API using ASP.NET MVC.

Add below Code to your index.

  • using System.Net » For Webclient(). Which is use to connect to our Web API
  • using System.Data » For DataTable()
  • using Newtonsoft.Json » JSON
  • Viewbag.Name = response » dynamically share values from our controller to our view.
  • John » Parameter value. It could be anything you want to supply.

 

Code:

The image below is the screenshot of my HomeController code.

Home Controller Code

4. Now to display this in our view and to make it as simple as possible I use ViewBag Property to pass data to our view. Now navigate to your View (index.cshtml) under Views->Home folder and open index.cshtml.

Index.cshtml

5. Replace the code from your actual index.cshtml using the code shown in the image below. This display whatever we save to our ViewBag.Name Property.

Index.cshtml

6. Lastly, Run your project using f5 to run your project in debugging mode or CTRL + f5 to run project without debugging mode. This should output parameter name we declare in this code from our index() method in HomeController.

  • string url = “http://localhost:41480/Home/HelloWorld?name=” + “John”;

If we replace the name parameter John into Regie from the code above the output should now be Hello Regie. But because I use John in my code the image below shows Hello John output.

 

Note:  Because we are using local project you need to run both API and client application to access both project. You can also publish your API in your local IIS read this thread How to Host ASP.NET Web App in IIS.

 

Output

That’s all we need in consuming Web API in ASP.NET.

Comments are greatly appreciated to improve my blog writing technique.

Thank you for reading. Happy Coding!

You might to want to revisit this blog  Create Web API in ASP.NET.


Post you may like:

[pt_view id=”2384ae03it”]

Leave a Reply

Your email address will not be published. Required fields are marked *