ASP.NET WEb APi


Agenda

  1. What is ASP.NET Web API?
  2. Creating Web APIs
  3. Routing and Actions
  4. Action Filters
  5. Model Binding
  6. Migration Manager
What is ASP.NET Web API?
  • Powerful platform for building APIs that expose services and data.
  • ASP.NET Web API is a framework for building RESTful web APIs on top of the .NET Framework.

Why Use ASP.NET Web API?
  • HTTP is simple, flexible, and ubiquitous.
  • HTTP can reach a broad range of clients, including browsers, mobile devices, and traditional desktop applications.

Creating Web APIs


  • Web API that supports CRUD Operations
  • MVC
    • Models
    • Views
    • Controllers
  • Contexts

CRUD Operations (Products example)

  • Create, Read, Update, Delete (CRUD)


Model

  • Plain Old CLR Object (POCO)
 
 public class Product
 {
     public int ProductId { get; set; }
     public string ProductName { get; set; }

     public int PersonId { get; set; }
 }
public class Person { public int PersonId { get; set; } public string FirstName { get; set; } public string LastName { get; set; }   public virtual ICollection<Product> Products { get; set; } }

Controller

  • A Controller is a class that handles HTTP requests from the clients.

 private MVC4WebApiContext db = new MVC4WebApiContext();

 // GET api/Persons
 public IEnumerable<Person> GetPeople()
 {
    return db.People.AsEnumerable();
 }

Context

  • DbContext: Primary object for interacting with a database using a specific Model.
  • DbSet: Used to perform CRUD operations against a specific type from a Model.
 public class MVC4WebApiContext : DbContext
 {
     public MVC4WebApiContext() : base("name=MVC4WebApiContext")
     {
     }

     public DbSet<Person> People { get; set; }
     public DbSet<Product> Products { get; set; }
 }

Routing

  • Routing Tables
 public static void Register(HttpConfiguration config)
 {
      config.Routes.MapHttpRoute(
          name: "DefaultApi",
          routeTemplate: "api/{controller}/{id}",
          defaults: new { id = RouteParameter.Optional }
      );

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

ActionS Methods


    
[HttpGet][ActionName("Beer")]// GET api/Products/Beer public IEnumerable<Product> GetProducts() { return db.Products.AsEnumerable().Where(x => x.productName == "Beer"); }

Model Binding

  • Using [FromUri]
 public HttpResponseMessage PostProduct([FromUri] int id){}
  • Using [FromBody]
 public HttpResponseMessage PostProduct([FromBody] Product product){}
  • IModelBinder
 public Product GetProduct([ModelBinder(typeof(CustomModelBinder))]string id){}

I Model Binder

 public class CustomModelBinder : IModelBinder
    {
        public bool BindModel(System.Web.Http.Controllers.HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            ValueProviderResult val = bindingContext.ValueProvider.GetValue(
                bindingContext.ModelName);

            if (val == null)
            {
                return false;
            }

            string newVal = "Hello!";

            bindingContext.Model = newVal;
            return true;
        }
    }

Action Filters

  1. Authorization Filters
  2. Action Filters
  3. Result Filters
  4. Exception Filters

Action Filter Attribute

 public class CustomActionFilter : ActionFilterAttribute
 {
    public override void OnActionExecuted(        HttpActionExecutedContext actionExecutedContext){}

    public override void OnActionExecuting(           HttpActionContextactionContext){} }
[CustomActionFilter] public class ProductsController : ApiController {}

Migration Manager

Package Manger Console
PM> Enable-Migrations -EnableAutomaticMigrations -Force
PM> Update-Database

Useful links

ASP.NET WEb APi

By Corey McGrillis