Skip to content

Instantly share code, notes, and snippets.

@diegocaxito
Last active September 27, 2015 15:48
Show Gist options
  • Save diegocaxito/1294187 to your computer and use it in GitHub Desktop.
Save diegocaxito/1294187 to your computer and use it in GitHub Desktop.
WCF Web Api with generic get method
using System.Linq;
using System.Net;
using System.ServiceModel;
using System.ServiceModel.Web;
using ContactManager.Infrastructure;
using ContactManager.Repositories;
using ContactManager.Resources;
using Microsoft.ApplicationServer.Http.Dispatcher;
namespace ContactManager.APIs
{
[ServiceContract]
public interface IBaseApi<T> where T : Entity
{
[WebGet]
IQueryable<T> Get();
}
public abstract class BaseApi<T> : IBaseApi<T> where T : Entity
{
protected IRepository<T> repository;
public IQueryable<T> Get()
{
return repository.FindAll().AsQueryable();
}
}
public class PeoplesApi : BaseApi<People>
{
public PeoplesApi()
{
repository = new PeopleRepository();
}
}
public class ContactsApi : BaseApi<Contact>
{
public ContactsApi()
{
repository = new ContactRepository();
}
[WebGet(UriTemplate = "{id}")]
public Contact GetItem(int id)
{
var contact = repository.Find(id);
contact.AssertIsNotNull();
return contact;
}
[WebInvoke]
public Contact Post(Contact contact)
{
repository.Add(contact);
return contact;
}
[WebInvoke(UriTemplate = "{id}")]
public Contact Put(Contact contact, int id)
{
var existingContact = repository.Find(id);
existingContact.AssertIsNotNull();
existingContact.Name = contact.Name;
return existingContact;
}
[WebInvoke(UriTemplate = "{id}")]
public Contact Delete(int id)
{
var contact = repository.Find(id);
contact.AssertIsNotNull();
repository.Remove(id);
return contact;
}
}
public static class WebExtentions
{
public static void AssertIsNotNull<T>(this T value) where T : Entity
{
if (value == null)
throw new HttpResponseException(HttpStatusCode.NotFound);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment