-
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 + WebApi 2) or ISession
(.NET 4.0 + WebApi).
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 example below is based upon all action filters being registered - hence the lack of null checks & model state validation code):
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 Task<HttpResponseMessage> Delete(int id)
{
return this.DeleteEntityResponseAsync(id);
}
public Task<HttpResponseMessage>Get(int id)
{
return this.GetEntityResponseAsync(id);
}
public Task<HttpResponseMessage>Post(Customer entity)
{
return this.PostEntityResponseAsync(entity);
}
public Task<HttpResponseMessage> Put(int id, Customer entity)
{
return this.PutEntityResponseAsync(id, entity);
}
}
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 utilize it you simply create a public method with a return type of Task<HttpResponseMessage>
`HttpResponseMessage` and call the relevant protected method supplied by the base class.
The approach makes it easy for you to specify which behavior you want in a particular controller and also works with the WebApi help page project.