-
Notifications
You must be signed in to change notification settings - Fork 1
Controllers
The easiest way to get started is to inherit your controller from the MicroLiteApiController
. This will give you a Session
property which is an IAsyncSession
(.NET 4.5 + MVC 5) or ISession
(.NET 4.0 + MVC 4).
public class CustomerApiController : MicroLiteApiController
(There is also a MicroLiteReadOnlyApiController
if you only want access to an IAsyncReadOnlySession
/IReadOnlySession
).
You can then use the Session to communicate with the database (the examples below assume all the attributes have been registered, hence the lack of null and model state checks):
public async Task<Customer> Get(int id)
{
return await this.Session.SingleAsync<Customer>(id);
}
public async Task Post(Customer customer)
{
await this.Session.UpdateAsync(customer);
}
public Customer Get(int id)
{
return this.Session.Single<Customer>(id);
}
public void Post(Customer customer)
{
this.Session.Update(customer);
}
The extension also includes a MicroLiteApiController<T>
class which provides the basic CRUD methods with minimal code (the example below is based upon all action filters being registered - hence the lack of null checks & model state validation code):
public class CustomerApiController : MicroLiteApiController<Customer, int>
{
public HttpResponseMessage Delete(int id)
{
return this.DeleteEntityResponse(id);
}
public HttpResponseMessage Get(int id)
{
return this.GetEntityResponse(id);
}
public HttpResponseMessage Post(Customer entity)
{
return this.PostEntityResponse(entity);
}
public HttpResponseMessage Put(int id, Customer entity)
{
return this.PutEntityResponse(id, entity);
}
}
The functionality is always opt-in, in order to utilise it you simply create a public method with a return type of HttpResponseMessage
and call the relevant protected method supplied by the base class.
The approach makes it easy for you to specify which behaviour you want in a particular controller and also works with the WebApi help page project.