Best practices in using the ASP.NET Web API

ASP.NET Web API is an ideal platform for building RESTful applications on the .NET framework. The ASP.NET Web API is a framework that can be used to build Http services regardless of REST or RPCβ€”it is Microsoft's best implementation of RFC. It allows both IIS and self hosting, and is asynchronous. The Web API is flexible and provides support for separation of concerns. It enables you to expose applications, data, and services to the Web directly over the HTTP protocol. The ASP.NET Web API relies on basic protocol and formats, such as HTTP, WebSockets, SSL, JQuery, JSON, and XML. There is no support for higher level protocols, such as Reliable Messaging or Transactions.

Here's a quick glance at the best practices and tips that you can follow when using the Web API:

  • You should use a custom base WebApiController where you can abstract the controller features and behavior
  • Use a URL helper for filtering all the image URLs
  • Always install the MvcRoutingShim plugin to avoid subtle and confusing behavior with multiple HTTP modules
  • It is advisable to create a separate controller for each resource

The following code is a quick look at the Base API controller for the Web API we created earlier in this book. The BaseApiController class extends the ApiController class, and implements the IBaseApiController interface.

public interface IBaseApiController : IDisposable
{
  Int32 ID { get; set; }        
}

public class BaseApiController<T> : ApiController where T : class, IBaseApiController
{
  BaseRepository<SecurityEntities> repository = null;
  protected string[] includesArray { get; set; }
  public BaseApiController()
  {
    repository = new BaseRepository<SecurityEntities>("SecurityEntities");
  }

  public virtual IEnumerable<T> Get()
  {
    return repository.GetData<T>(includesArray);
  }

  public virtual T Get(Int32 id)
  {
    return repository.SearchData<T>(t => t.ID == id, includesArray);
  }

  public virtual Int32 Post([FromBody]T value)
  {
    return repository.EditData<T>(value);
  }

  public virtual Int32 Put([FromBody]T value)
  {
    return repository.CreateData<T>(value);
  }

  public virtual Int32 Delete([FromBody]T value)
  {
    return repository.RemoveData<T>(value);
  }
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset