Jayakumar Jayakumar - 3 months ago 24
ASP.NET (C#) Question

Asp.net Web API Server and client application

I am new in Asp.net Web API development. I want to develop Web API RestFul service using Asp.Net Web API and Consume the client application.
So, How to create Http verbs - GET,POST,PUT and DELETE method in Server and consume using httpclient in Asp.net application.

Thanks in advance.

Answer

To Create a Asp.net Web API Application. Explain two application step by step.

1.Asp.Net Web API Creation 2.Consume Asp.Net Web API in Asp.Net MVC Application

Asp.Net Web API Creation

In visual studio - Create New Project -> Asp.Net Web Application -> Web API [Change Authentication -> No Authentication] -> Click OK

Small code change in WebApiConfig.cs

By default

        config.MapHttpAttributeRoutes();

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

To add bellow code :

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

This Web Api application access Library function used by bellow files and its get data from database.

  • SettingsBO
  • ShipmentBO

I have develop the GET and POST method functionality bellow

namespace MyFirstWebAPI.Controllers
{

[RoutePrefix("api/Product")]
public class ProductController : ApiController
{
    [HttpGet]
    [Route("GetAllPorts")]
    public async Task<IEnumerable<Port>> GetAllPorts()
    {
        try
        {
            IEnumerable<Port> port = await SettingsBO.GetPortAsync();
            return port;
        }
        catch (Exception ex)
        {
            var err = ex.Message.ToString().Replace("\n", "N^^").Replace("\r", "R^^");
            var resp = new HttpResponseMessage(HttpStatusCode.NotFound)
            {
                Content = new StringContent(string.Format("Error Message = {0}", err)),
                ReasonPhrase = err
            };
            throw new HttpResponseException(resp);
        }
    }

    [HttpGet]
    [Route("GetShipmentDetails/{shipmentLId}/{orderid}")]
    public async Task<ShipmentLegViewModel> GetShipmentDetails(string shipmentLId, string orderid)
    {
        try
        {
            ShipmentLegViewModel shipmentDet = await ShipmentBO.GetSegmentLegDetailsAsync(shipmentLId, orderid);
            return shipmentDet;
        }
        catch (Exception ex)
        {
            var err = ex.Message.ToString().Replace("\n", "N^^").Replace("\r", "R^^");
            var resp = new HttpResponseMessage(HttpStatusCode.NotFound)
            {
                Content = new StringContent(string.Format("Error Message = {0}", err)),
                ReasonPhrase = err
            };
            throw new HttpResponseException(resp);
        }
    }

    [HttpPost]
    [Route("UpdatePort")]
    public async Task<string> UpdatePort(List<PortUpdate> port, string Id, string portStatusId)
    {
        try
        {
            return await SettingsBO.UpdateItemAsync(Id, port, portStatusId);
        }
        catch (Exception ex)
        {
            var err = ex.Message.ToString().Replace("\n", "N^^").Replace("\r", "R^^");
            var resp = new HttpResponseMessage(HttpStatusCode.NotFound)
            {
                Content = new StringContent(string.Format("Error Message = {0}", err)),
                ReasonPhrase = err
            };
            throw new HttpResponseException(resp);
        }
    }
}

}

Above code is helps to create Asp.Net Web API Application. Buid and run the application using bellow structure.

URL : http://localhost:4314/api/Product/GetAllPorts

2.Consume Asp.Net Web API in Asp.Net MVC Application

I have create a Asp.Net MVC Application.

You should add web api package for client application

Install-Package Microsoft.AspNet.WebApi.Client

create a specific class [Webservice.cs] to access Web API data. Given bellow code

namespace WebAPI_Client.CNHService
{
public static class WebService<T> where T : class
{
    public static string appSettings = ConfigurationManager.AppSettings["ServiceURL"];

    public static IEnumerable<T> GetDataFromService(string Method, string param = "")
    {
        WebClient client = new WebClient();
        try
        {
            var data = client.DownloadData(appSettings + Method + param);
            var stream = new System.IO.MemoryStream(data);
            var obj = new DataContractJsonSerializer(typeof(IEnumerable<T>));
            var result = obj.ReadObject(stream);
            IEnumerable<T> Ts = (IEnumerable<T>)result;
            return Ts;
        }
        catch (WebException wex)
        {
            throw;
        }
        catch (Exception ex)
        {
            throw;
        }
    }

    public static T GetDataFromService_SingleCollection(string Method, string param = "")
    {
        try
        {
            var client = new WebClient();
            var data = client.DownloadData(appSettings + Method + param);
            var stream = new System.IO.MemoryStream(data);
            var obj = new DataContractJsonSerializer(typeof(T));
            var result = obj.ReadObject(stream);
            T Ts = (T)result;
            return Ts;
        }
        catch (Exception ex)
        {
            throw;
        }
    }


    public static async Task<T> GetShipmentDetails(string shipmentLId,string orderid)
    {
        Stream stream = null;
        T Ts = null;
        string url = "http://localhost:4314/api/Product/GetShipmentDetails/5462f4e3e4b09e0d94f5c9a2/5462f4e2e4b09e0d94f5c9a1";
        try
        {
            using (HttpClient client = new HttpClient())
            {
                client.BaseAddress = new Uri(url);
                HttpResponseMessage response = await client.GetAsync(url);
                if (response.IsSuccessStatusCode)
                {
                    var data = await response.Content.ReadAsByteArrayAsync();
                    var stre = new System.IO.MemoryStream(data);
                    var obj1 = new DataContractJsonSerializer(typeof(IEnumerable<T>));
                    var result = obj1.ReadObject(stre);
                    Ts = (T)result;
                }
                else
                {
                    stream = await response.Content.ReadAsStreamAsync();
                    var error = await response.Content.ReadAsStringAsync();
                }
                return Ts;
            }
        }
        catch (Exception ex)
        {

        }
        return Ts;
    }

    public static async Task<IEnumerable<T>> GetPorts()
    {
        Stream stream = null;
        IEnumerable<T> Ts = null;
        string url = "http://localhost:4314/api/Product/GetAllPorts";
        try
        {
            using (HttpClient client = new HttpClient())
            {
                client.BaseAddress = new Uri(url);
                HttpResponseMessage response = await client.GetAsync(url);
                if (response.IsSuccessStatusCode)
                {
                    var data = await response.Content.ReadAsByteArrayAsync();
                    var stre = new System.IO.MemoryStream(data);
                    var obj1 = new DataContractJsonSerializer(typeof(IEnumerable<T>));
                    var result = obj1.ReadObject(stre);
                    Ts = (IEnumerable<T>)result;
                }
                else
                {
                    stream = await response.Content.ReadAsStreamAsync();
                    var error = await response.Content.ReadAsStringAsync();
                }
                return Ts;
            }
        }
        catch (Exception ex)
        {

        }
        return Ts;
    }

    public static async Task<IEnumerable<T>> GetDataFromService_Update(string Method, List<Port> portData, string param = "")
    {
        try
        {
            string requestUri = Method + param;
            string url = "http://localhost:4314/";
            IEnumerable<T> Ts = null;
            using (HttpClient client = new HttpClient())
            {
                client.BaseAddress = new Uri(url);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                HttpResponseMessage response = await client.PostAsJsonAsync(requestUri, portData);
                if (response.IsSuccessStatusCode)
                {
                    var res = await response.Content.ReadAsStringAsync();
                }
                else
                {
                    var error = await response.Content.ReadAsStringAsync();
                }
            }
            return Ts;
        }
        catch (Exception ex)
        {
            throw;
        }
    }
}

}

Controller code

For GET and POST Method

 public class HomeController : Controller
{
    public async Task<ActionResult> Index()
    {
         //GET Method      
         IEnumerable<Port> portq = await CNHService.WebService<Port>.GetPorts();
         //POST Method      
         List<Port> port = portq.ToList<Port>();
         IEnumerable<string> resUpdate = await CNHService.WebService<string>.GetDataFromService_Update("api/Product/UpdatePort", port, "?Id=5462f4d8e4b09e0d94f5c96f&portStatusId=5462f4d8e4b09e0d94f5c96c");
    }
}

Above code is working fine to get and post method.

This code is more help to your Web API application development