Skip to content
This repository has been archived by the owner on Oct 27, 2020. It is now read-only.

Controllers

Trevor Pilley edited this page Jan 6, 2015 · 7 revisions

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):

.NET 4.5 + WebApi 2 Examples

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);
}

.NET 4.0 + WebApi Examples

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):

.NET 4.5 + WebApi 2 Example

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);
    }
}

.NET 4.0 + WebApi Examples

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.

Clone this wiki locally