Create ASP.NET Web API Project with RavenDB
In this section we will go over the steps to creating you own ASP.NET Web API Application.
Step by Step Instructions
- Make sure you have ASP.NET Web API installed.
- In visual studio and create a new "ASP.NET MVC 4 Web Application" project.
- As Project template select "Web API".
- Add the NuGet Package named "RavenDB Client".
- Create the following controller:
public abstract class RavenDbController : ApiController
{
public IDocumentStore Store
{
get { return LazyDocStore.Value; }
}
private static readonly Lazy<IDocumentStore> LazyDocStore = new Lazy<IDocumentStore>(() =>
{
var docStore = new DocumentStore
{
Url = "http://localhost:8080",
DefaultDatabase = "WebApiSample"
};
docStore.Initialize();
return docStore;
});
public IAsyncDocumentSession Session { get; set; }
public async override Task<HttpResponseMessage> ExecuteAsync(
HttpControllerContext controllerContext,
CancellationToken cancellationToken)
{
using (Session = Store.OpenAsyncSession())
{
var result = await base.ExecuteAsync(controllerContext, cancellationToken);
await Session.SaveChangesAsync();
return result;
}
}
}
- From now on write you application as you would normally but Inherit from RavenDbController in any controller you want to contact RavenDB
Example of a controller:
public class SampleController : RavenDbController
{
public Task<IList<string>> GetDocs()
{
return Session.Query<WebData>().Select(data => data.Name).ToListAsync();
}
public async Task<HttpResponseMessage> Put([FromBody]string value)
{
await Session.StoreAsync(new WebData { Name = value });
return new HttpResponseMessage(HttpStatusCode.Created);
}
}