Chlodny series Day 6: ASP.NET Web API Get configuration

ASP.NET Web API exposes data through a controller called an API controller.  This controller can be added to an existing controller.  To add a new controller:

Right-click the controllers folder in the ChlodnyWebApi project and select Add –> Controller. In the dialog box, name the new controller ‘CustomerController’ and for template select ‘Empty API controller’.

CropperCapture[54]

Click Add, there will now be an empty CustomerController.cs that will look similar to this.

namespace ChlodnyWebApi.Controllers
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using DataAccess;
using DataAccess.Entities;

    public class CustomerController : ApiController
{
}
}

For the initial Get method example, one method does not take a parm and the second one does.  First one will return and IEnumerable of all customers and the other will return a single customer based on the customer id passed in.  The two methods will look like this:

public IEnumerable<Customer> GetCustomer()
{
using (var context = new ChinookContext())
{
return context.Customers.ToList();
}
}

public Customer GetCustomer(int id)
{
using (var context = new ChinookContext())
{
return context.Customers.Single(c => c.CustomerId == id);
}
}

  • Now build the project and start
  • Open Fiddler
  • Under composer select the GET verb
  • Enter the address http://localhost:60025/api/customer(change the port to to match)
  • Click Execute
  • Under Web Sessions select the following:

CropperCapture[63]

  • Fiddler should switch to the Inspector and look similar to this (including all the customer records in the Chinook database).

CropperCapture[64]

CropperCapture[65]

This will now return only the record with customer id equal to 1.

Advertisement
This entry was posted in MVC, Web and tagged , , , , . Bookmark the permalink.