Monday, 24 July 2017

HTTP Get, Put, Post And Delete Verbs In ASP.NET WEB API


Introduction
In this article, I will explain about Http Get, Put, Post and Delete verbs in ASP.Net Web API in detail. These are very significant verbs in ASP.NET Web API. This article explains how to perform these 4 verbs in ASP.NET Web API.

Steps for performing HTTP verbs using ASP.NET web API
The steps given below explain about how HTTP verbs perform with ASP.NET Web API.
Step 1
Open new project in Visual Studio, select the Web under visual C# and select ASP.NET Web Application. Finally, give the project name and click OK. Now, select Web API from template Window and click OK.

After opening the project solutions, we can see the all folders in Solution Explorer. Everything is same as ASP.NET MVC but we can find one extra controller and this controller is Value controller. Value controller is inherited from APIController. APIController is an abstract class. Before reading this article, please refer to the article, as it helps to know about APIControllers and API routing.\
Step 2
We can find the five methods in ValuesController. ValuesController looks, as shown below.

For multiple parameters:

"/home/MultipleParameter/?data1=678&data2=c-sharpcorner">
public ActionResult MultipleParameter(int data1, string data2)
        {
}

http://localhost:1562/idlang/0/1

[Route("idlang/{id=range(0,1)}/{id2}")]
        public string Get(int id,int id2)
        { 
        return  language[id];

        }


In this Controller, we create one static variable with the type of list. In this variable, we assign three strings.
Example 
  1. static List<string> languages = new List<string>() {   
  2.             "C#","ASP.NET","MVC"  
  3.         };  
Get method returns what are the strings assigned in the languages variable. Get method contains the code, which looks, as shown below. 
  1. // GET api/values  
  2.        public IEnumerable<string> Get()  
  3.        {  
  4.            return languages;  
  5.        }   
If need arises, you can get the specified string from the list. We can get it, using Get method with the parameter. Here, Get method contains overload. 
  1. // GET api/values/5  
  2.        public string Get(int id)  
  3.        {  
  4.            return languages[id];  
  5.        }   
If need to Add or Save data in the list arises, we can use Post method. For Post method, we use code given below. 
  1. // POST api/values  
  2.         public void Post([FromBody]string value)  
  3.         {  
  4.             languages.Add(value);  
  5.         }   
We can update and delete the data in the list, using the code given below. 
  1. // PUT api/values/5  
  2.        public void Put(int id, [FromBody]string value)  
  3.        {  
  4.            languages[id] = value;  
  5.        }  
  6.   
  7.        // DELETE api/values/5  
  8.        public void Delete(int id)  
  9.        {  
  10.            languages.RemoveAt(id);  
  11.        }   
Step 3
We are using Fiddler for monitoring Get, Put, Post, Update actions in Web API. We can download it for free from the URL “https://www.telerik.com/download/fiddler” and install it.
Now, build the project solution and run it. I am running URL http://localhost:51860/api/values/. Now, it will call Get action method in ValueController. Put a breakpoint and you can see which method calls in ValueControllers.



When we put above-mentioned output without the parameter, it automatically calls Get method in Web API. After returning an output, we can see the output as an XML, which is shown below.

If we pass index value of the list, we can get a particular string from the list. I am giving http://localhost:51860/api/values/1 so, it will return “ASP.NET” because it has an index value 1.


Step 4
Now, open Fiddler and using it, we can monitor POST, PUT and delete. First, run the Application and then copy http://localhost:51860/api/values URL past in Fiddler in composer tab, followed by clicking enter.

Now, double click the latest URL on the left side in Fiddler and you can view the result. This will show the type of result and request header details.

First, refresh the Application in the Browser. Now, go to composer tab, select GET in the drop-down list and click. Track the latest URL from the left side to composer tab. We can see all details like Host, Connection, Catch-Control, User-Agent and Accept details. 



Now, add new string, using post HTTP verb, how to add and again get back from the list, using Fiddler.
Go to composer tab, select POST in the drop-down list and add new string or value in Request body and add Content-Type: application/JSON, followed by clicking Execute button in right side top.

Now, double click the latest URL on the left side of Fiddler and you can see the response of giving Post request in Fiddler. We can see the response is 204 No Content because post action method is void return type.

Now, we can check whether a string is added in a static variable. Now, select get request and delete added string in request body and click execute. Now, double click the latest one on the left side in Fiddler and you can see added string, which looks as shown below.

Now, we can update the last string in a static variable, using PUT HTTP verb in Fiddler. Now, select PUT from the dropdown in composer tab and the type where we want a new string to update the old string, followed by passing the index value to update the string in the URL and click execute button.

Now, refresh the page and get a new one on the left side of Fiddler. Double-click it and we can see the updated string in Fiddler.

Similarly, we can delete the string from a static variable. Similar to selecting Delete HTTP verb, pass an index value of the one, which needs to be deleted from a static variable. After clicking executes, it refreshes our application. For reference, view the screenshot given below.







Get,Save,Update,Delete with entity framwork


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

namespace BookTicketService.Controllers

{
    [RoutePrefix("User")]
    public class UserController : ApiController
    {

        [Route("GetUserInfo")]

        public IEnumerable<UserInfo> GetUserInfo()
        {
            using (BookTicketEntities entities = new BookTicketEntities())
            {
                return entities.UserInfoes.ToList();
            }
        }

        [Route("GetUserInfo/{UserId}")]

        public UserInfo GetUserInfo(int id)
        {
            using (BookTicketEntities entities = new BookTicketEntities())
            {

                return entities.UserInfoes.FirstOrDefault(x => x.UserID == id);

            }
        }

       // [HttpPost]

        [Route("SaveUserDetails")]
        public IHttpActionResult SaveUserDetails(UserInfo userInfo)
        {
            using (BookTicketEntities entities = new BookTicketEntities())
            {
               
                entities.UserInfoes.Add(userInfo);
                if (entities.SaveChanges() == 1)
                    return Created("http://localhost:57292/User/SaveUserDetails/userInfo", userInfo);
                else
                  return  InternalServerError();

            }

        }


        [HttpPut]

        [Route("UpdateUserDetails")]
        public HttpResponseMessage UpdateUserDetails([FromBody]UserInfo userInfo)
        {
            using (BookTicketEntities entities = new BookTicketEntities())
            {
                entities.UserInfoes.Attach(userInfo);
                entities.Entry(userInfo).State = EntityState.Modified;
                entities.SaveChanges();
               // if (entities.SaveChanges() == 1)
                    return Request.CreateResponse(HttpStatusCode.OK, userInfo);
                //else
                //    Request.CreateResponse(HttpStatusCode.InternalServerError, userInfo);

            }

        }

        [HttpDelete]

        [Route("DeleteUser/{UserId}")]
        public HttpResponseMessage DeleteUser([FromUri] int  UserId)
        {
            using (BookTicketEntities entities = new BookTicketEntities())
            {
                try
                {
                    var userInfo = entities.UserInfoes.Where(x => x.UserID == UserId).FirstOrDefault();
                    entities.UserInfoes.Remove(userInfo);


                    return Request.CreateResponse(HttpStatusCode.OK);

                }
                catch (ArgumentNullException ex)
                {
                    return Request.CreateResponse(HttpStatusCode.NoContent);
                }

            }

        }
       
    }
}

No comments:

Post a Comment