Last active
September 27, 2015 15:48
-
-
Save diegocaxito/1294187 to your computer and use it in GitHub Desktop.
WCF Web Api with generic get method
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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