Create and Consume REST API webservices in ASP.NET MVC

  • by
rest_api_mvc_thumbnail

In this post we will see How we can create REST API in ASP.NET MVC. We will create a simple API which will have POST and GET methods and it will work as a calculation tool for the numbers provided. This will be a very simple and easy to understand example. In the later post we will do more complex task using REST API webservices.
So let’s begin.

REST stands for Representational State Transfer. REST is an architectural pattern for creating webservices. Mostly in REST API data is used as JSON objects (for posting and responsing).

DOWNLOAD SOURCE CODE

Creating REST API Webservice:
In your MVC project, create a new controller in APIControllers folder with name CalciController.cs and edit it as below:

APIControllers > CalciController.cs:

using RestAPIEx.Models;
using System;
using System.Web.Http;

namespace RestAPIEx.APIControllers
{
public class CalciController : ApiController
{

[Route("api/Calculations")]
[HttpPost]
public Result AddEvents(Numbers obj)
{
Result res = new Result();
try
{
switch (obj.calcType)
{
case "+":
res.result = (obj.num1 + obj.num2).ToString();
break;
case "-":
res.result = (obj.num1 - obj.num2).ToString();
break;
case "*":
res.result = (obj.num1 * obj.num2).ToString();
break;
case "/":
res.result = (obj.num1 / obj.num2).ToString();
break;
default:
res.result = (obj.num1 + obj.num2).ToString();
break;
}
}
catch (Exception ex)
{
res.result = "Error : " + ex.Message.ToString();
}
return res;
}

}
}

The method is pretty self-explanatory. It will switch on type of parameter in the “calcType” string object and do calculation and return the result. Here

[Route(“api/Calculations”)]
[HttpPost]
public Result AddEvents(Numbers obj)

is important to understand. We are creating a HttpPost web-request (for get method using [HttpGet]). Since we are creating a calculator like method I’m using HttpPost method. Your Route will define the URL path using which webservice will be accessed by browser. Here it can be accessed using :

BaseURL/api/Calculations/

Create a new Model class with name Numbers.cs and edit it as below:

Models>Numbers.cs:

namespace RestAPIEx.Models
{
public class Numbers
{
public int num1 { get; set; }
public int num2 { get; set; }

public string calcType { get; set; }
}

public class Result
{
public string result { get; set; }
}
}

Edit the WebApiConfig.cs class in your App_Start folder as following to accept the JSON objects posted by users.

App_Start > WebApiConfig.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;

namespace RestAPIEx
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services

// Web API routes
config.MapHttpAttributeRoutes();

config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);

GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling
= Newtonsoft.Json.ReferenceLoopHandling.Ignore;

var json = config.Formatters.JsonFormatter;

json.SerializerSettings.PreserveReferencesHandling =
Newtonsoft.Json.PreserveReferencesHandling.Objects;
config.Formatters.Remove(config.Formatters.XmlFormatter);

var json4 = config.Formatters.JsonFormatter;
json4.SerializerSettings.PreserveReferencesHandling
= Newtonsoft.Json.PreserveReferencesHandling.None;
}
}
}

Note: Without this code, your project will still build successfully, but will not be able to parse JSON objects.

GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling
= Newtonsoft.Json.ReferenceLoopHandling.Ignore;

var json = config.Formatters.JsonFormatter;

json.SerializerSettings.PreserveReferencesHandling =
Newtonsoft.Json.PreserveReferencesHandling.Objects;
config.Formatters.Remove(config.Formatters.XmlFormatter);

var json4 = config.Formatters.JsonFormatter;
json4.SerializerSettings.PreserveReferencesHandling
= Newtonsoft.Json.PreserveReferencesHandling.None;

Result:

RESTAPI MVC - RESULT Addition

RESTAPI MVC – RESULT Addition

 

RESTAPI MVC - RESULT Division

RESTAPI MVC – RESULT Division

DOWNLOAD SOURCE CODE

Consuming the REST API in .NET MVC forms:

Let’s now use the RESTful APIs we just created on to our MVC forms.

Create a new Controller with name CalciController.cs and edit it as below:

Controllers>CalciController.cs:

using RestAPIEx.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web;
using System.Web.Mvc;

namespace RestAPIEx.Controllers
{
public class CalciController : Controller
{
// GET: Calci
public ActionResult Index()
{
ViewBag.Result = "Enter numbers in Textboxes.";
return View();
}

[HttpPost]
public ActionResult Index(Numbers numbers)
{
try
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost/RestAPIEx/api/");

var postObj = client.PostAsJsonAsync<Numbers>("Calculations", numbers);
postObj.Wait();

var res = postObj.Result;

var result = res.Content.ReadAsAsync<Result>().Result.result;

ViewBag.Result = result;
}
}
catch (Exception ex)
{
ViewBag.Result = "Error:" + ex.Message.ToString();
}
return View();

}

}
}

If you getting errors on this class file, please check if you have nuget package Microsoft.AspNet.WebApi.Client installed on your project.

Microsoft_AspNet_WebApi_Client01_RESTAPI_Project

Microsoft_AspNet_WebApi_Client01_RESTAPI_Project

Add a View with model class as Numbers.cs (Models>Numbers.cs).

Views>Calci>Index.cshtml:

@model RestAPIEx.Models.Numbers

@{
Layout = null;
}

<!DOCTYPE html>

<html>
<head>
<meta name="viewport" content="width=device-width" />
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<style>
body
{
padding:5px;
}
input[type="text"]
{
border:1px solid #000;
padding:5px;
border-radius:2px;
width:70px;
}
</style>
<title>Index</title>
</head>
<body>
<div>

@using (Html.BeginForm())
{
<h2>Consuming REST API:</h2>
@Html.TextBoxFor(m => m.num1)
<span>&nbsp;&nbsp;</span>
@Html.TextBoxFor(m => m.calcType)
<span>&nbsp;&nbsp;</span>
@Html.TextBoxFor(m => m.num2)
<br /><br />

<input value="submit" type="submit" title="Add" class="btn btn-success"/>
<br />
<br />
@ViewBag.Result
}
</div>
</body>
</html>

Output:

mvc_restapi_consuming_webservice

mvc_restapi_consuming_webservice

DOWNLOAD SOURCE CODE