How to implement GET method with MVC REST WebApi

In my previous post about WebApi development using MVC, I discussed basic requirements to get started with WebApi in MVC4. In this post, I will discuss how to go about implementing a simple method to perform GET action.

The building blocks of a REST WebApi using MVC4 is that method names in your Api controller define the mapping of HTTP method to a particular controller method. When you type a URL in a browser, behind the scene the browser sends a HTTP GET request to the server. Same concepts work for REST API as well. When we want to implement a method to GET some collection of objects or one object, client application will construct a HTTP GET request and send to your MVC based Web Api. MVC framework looks at the method type for HTTP requests and then calls that method on that controller.

GET Method

In my sample project for a trading platform development, I have built a Seller controller for WebApi. I want to perform all CRUD operations related to Seller management through this Api. Following are signatures of two methods that I implemented.

        public IQueryable<Models.TradingSeller> GetAllSellers()
        {....}

        public ISeller GetSeller(int ? id)
        {...}
    

The key to these controller methods in use of word Get as prefix. When controller receives a GET requests it automatically calls appropriate method depending on what extra parameters are passed in the request. If there are no parameters in request, then GetAllSellers method gets called. But if you will pass a numeric ID in query string of request, GetSeller method will be called. So the requests could look like as below.

  • http://trader.byterblocks.com/api/Sellers - Maps to GetAllSellers
  • http://trader.byteblocks.com/api/Sellers/1 - Maps to GetSeller

Implementing REST WebApi Client

Once you have implemented your RESt WebApi using MVC4, you would want to implement client request to execute these APIs. Following code snippet shows I build my client requests in a MVC web application that calls to a MVC WebApi.

private IQueryable<SellerModel> GetSellers()
{
   var gatewayClient = Trader.Dashboard.Helper.WebApiHelper.CreateServicesGatewayClient();
   try
   {
     HttpResponseMessage resp = gatewayClient.GetAsync("api/sellers").Result;
     resp.EnsureSuccessStatusCode();
     return resp.Content.ReadAsAsync<IEnumerable<Models.SellerModel>>().
        Result.AsQueryable<SellerModel>();
   }
   catch (HttpRequestException reqEx)
   {
     System.Diagnostics.Debug.Write(reqEx.Message);
     throw reqEx;
   }
   catch (Exception ex)
   {
     System.Diagnostics.Debug.Write(ex.Message);
     throw ex;
   }
}

public static HttpClient CreateServicesGatewayClient()
{
   var requestHandler = new WebRequestHandler()
   {
     AllowAutoRedirect = true,
     UseProxy = false
   };

   var httpClient = new HttpClient(requestHandler)
   {
      BaseAddress = new Uri(ConfigurationManager.AppSettings["TradingServicesGateway"])
   };
   httpClient.DefaultRequestHeaders.Accept.Add(
     new MediaTypeWithQualityHeaderValue("application/json"));
}          
    

The key in this request is GetAsync method call. This method sets HTTP request method type to GET. And then server side executes appropriate methods.

As you can see, how easy it is to develop a GET method for REST WebApi and easy to implement a C# client application to execute Api request. In next post I will discuss development of javascript client request to call MVC WebApi to fetch list of sellers from the server.

Search

Social

Weather

-0.8 °C / 30.6 °F

weather conditions Mist

Monthly Posts

Blog Tags