ASP.NET MVC – How to Create REST API Webservice

  • by
asp.net_mvc_restapi_http_post

In this post we will learn how we can create a rest api webservice in asp.net mvc. We will create both HttpPost and HttpGet webservice. The service will be having one class object as parameter and it will stored data in SQL Database once it is validated. The HttpGet service will simply return current date and time of system to the user as service response. So let’s begin. In previous we already discussed how to create basic rest api webservices in asp.net mvc.

DOWNLOAD SOURCE CODE

Database script:

--USE [ParallelCodes]
-----------------------------------------------------
CREATE TABLE [dbo].[Products](
[Id] [int] IDENTITY(1,1) NOT NULL,
[ProName] [nvarchar](50) NOT NULL,
[ProDesc] [nvarchar](100) NOT NULL,
[OnDate] [datetime] NULL DEFAULT (getdate())
)
-----------------------------------------------------
create procedure [dbo].[sp_AddProducts]
(
@ProName nvarchar(50), @Prodesc nvarchar(100)
)
as
begin
insert into Products (ProName,ProDesc) values (@ProName,@ProDesc)
end

In your project create a new API controller with name ProductsController and edit it as below:

YourProjectName > APIControllers > ProductsController.cs:

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

namespace RestAPIEx.APIControllers
{
public class ProductsController : ApiController
{

public static string connectionString = @"Data Source=192.168.0.103;Initial Catalog=ParallelCodes;User ID=sa;Password=789;Trusted_Connection=false;";
SqlConnection con;
SqlCommand cmd;

[Route("api/currentDate")]
[HttpGet]
public String GetDateTime()
{
return System.DateTime.Now.ToString();
}

[Route("api/AddProduct")]
[HttpPost]
public Result AddProducts(Products products)
{
Result rs = new Result();
if (products == null || String.IsNullOrWhiteSpace(products.productDesc) ||
String.IsNullOrWhiteSpace(products.productName))
{
rs.result = "Please provide Product name and Description.";
return rs;
}
try
{
con = new SqlConnection(connectionString);
cmd = new SqlCommand();
cmd.Connection = con;
con.Open();
cmd.CommandText = "sp_AddProducts";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@ProName", products.productName);
cmd.Parameters.AddWithValue("@Prodesc", products.productDesc);
cmd.ExecuteNonQuery();

cmd.Dispose();
con.Close();

rs.result = "Product details added successfully";
}
catch (Exception ex)
{
rs.result = ex.Message.ToString();
}
return rs;
}
}
}

The first method is HttpGet method. It does not have any passing parameter because it simply returns datetime and nothing else as its response.
The second method is our HttpPost service. This method accepts Product class parameter. This class must contain the information of Product name and product description which we will save in database after checking if it is null and whitespace.

Create a new Model class with name Products.cs in your project Models folder and edit it as below:

YourProjectName > Models > Products.cs:

namespace RestAPIEx.Models
{
public class Products
{
public string productName { get; set; }
public string productDesc { get; set; }
}
}

This is the passing parameter object of our HttpPost REST API webservice method. You can test this rest api example in Postman or implement in your ASP.NET Form or MVC applications. As it is accepting and response service call in JSON format, it is supported in all application languages.

Models > Result.cs:

public class Result
{
public string result { get; set; }
}
asp.net_mvc_restapi_http_post

asp.net_mvc_restapi_http_post

asp.net_mvc_restapi_http_get

asp.net_mvc_restapi_http_get

Edit your WebApiConfig.cs Register method as below:

YourProjectName>App_Start > WebApiConfig.cs:

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;
}
}
}

To see how to implement this service on .NET forms or MVC forms please see:

Consuming REST API webservice on .NET MVC forms 

DOWNLOAD SOURCE CODE