Skip to content

Instantly share code, notes, and snippets.

@JasonOffutt
Created October 22, 2011 18:41
Show Gist options
  • Save JasonOffutt/1306345 to your computer and use it in GitHub Desktop.
Save JasonOffutt/1306345 to your computer and use it in GitHub Desktop.
Dynamic Rest Service API using MVC Controllers
using System;
using System.Web.Mvc;
public interface IRestService<TEntity>
{
ActionResult List(string format = "");
ActionResult Show(int id, string format = "");
ActionResult Show(Guid guid, string format = "");
ActionResult Create(TEntity entity, string format = "");
ActionResult Update(TEntity entity, int id, string format = "");
ActionResult Destroy(int id, string format = "");
}
using System;
using System.Linq;
using System.Web.Mvc;
using System.Web.Security;
using Rock.Framework.Services.Crm;
using Rock.Helpers;
using Rock.Models.Crm;
using Rock.Services.Crm;
/// <summary>
/// Implementing a REST service as a group of MVC controllers give us lots of flexibility.
/// We lose some WCF features, but we gain the ability to define new functionality
/// on the fly rather than having to explicitly define new endpoints or maintain asingle large,
/// monolithic service.
/// </summary>
public class PersonController : RestControllerBase, IRestService<Person>
{
private readonly bool isAuthenticated;
private readonly MembershipUser currentUser;
public PersonController()
{
currentUser = Membership.GetUser();
isAuthenticated = currentUser != null;
}
[HttpGet]
public ActionResult List(string format = "")
{
if (!isAuthenticated)
{
return ByErrorCode(ErrorCode.Unauthenticated);
}
using (var uow = new UnitOfWorkScope())
{
uow.objectContext.Configuration.ProxyCreationEnabled = false;
var service = new PersonService();
var people = service.Queryable().Where(p => p.Authorized("View", currentUser));
return ByFormat(people, format);
}
}
[HttpGet]
public ActionResult Show(int id, string format = "")
{
if (!isAuthenticated)
{
return ByErrorCode(ErrorCode.Unauthenticated);
}
using (var uow = new UnitOfWorkScope())
{
uow.objectContext.Configuration.ProxyCreationEnabled = false;
var service = new TestPersonService();
var entity = service.GetByID(id);
if (entity.Authorized("View", currentUser))
{
return ByFormat(entity, format);
}
return ByErrorCode(ErrorCode.Forbidden);
}
}
[HttpGet]
public ActionResult Show(Guid guid, string format = "")
{
if (!isAuthenticated)
{
return ByErrorCode(ErrorCode.Unauthenticated);
}
using (var uow = new UnitOfWorkScope())
{
uow.objectContext.Configuration.ProxyCreationEnabled = false;
var service = new TestPersonService();
var entity = service.GetByGuid(guid);
if (entity.Authorized("View", currentUser))
{
return ByFormat(entity, format);
}
return ByErrorCode(ErrorCode.Forbidden);
}
}
[HttpPost]
public ActionResult Create(Person entity, string format = "")
{
if (!isAuthenticated)
{
return ByErrorCode(ErrorCode.Unauthenticated);
}
using (var uow = new UnitOfWorkScope())
{
try
{
uow.objectContext.Configuration.ProxyCreationEnabled = false;
var service = new TestPersonService();
service.Attach(entity);
service.Save(entity, (int)currentUser.ProviderUserKey);
return ByFormat(true, format);
}
catch
{
//ctx.OutgoingResponse.StatusCode = HttpStatusCode.InternalServerError;
return ByErrorCode(ErrorCode.ServerError);
}
}
}
[HttpPut]
public ActionResult Update(Person entity, int id, string format = "")
{
if (!isAuthenticated)
{
return ByErrorCode(ErrorCode.Unauthenticated);
}
using (var uow = new UnitOfWorkScope())
{
try
{
uow.objectContext.Configuration.ProxyCreationEnabled = false;
var service = new TestPersonService();
var existing = service.GetByID(id);
if (existing == null)
{
return ByErrorCode(ErrorCode.NotFound);
}
if (existing.Authorized("Edit", currentUser))
{
uow.objectContext.Entry(existing).CurrentValues.SetValues(entity);
service.Save(existing, (int)currentUser.ProviderUserKey);
}
else
{
return ByErrorCode(ErrorCode.Forbidden);
}
return ByFormat(true, format);
}
catch (Exception)
{
return ByErrorCode(ErrorCode.ServerError);
}
}
}
[HttpDelete]
public ActionResult Destroy(int id, string format = "")
{
if (!isAuthenticated)
{
return ByErrorCode(ErrorCode.Unauthenticated);
}
using (var uow = new UnitOfWorkScope())
{
try
{
uow.objectContext.Configuration.ProxyCreationEnabled = false;
var service = new TestPersonService();
var entity = service.GetByID(id);
if (entity == null)
{
return ByErrorCode(ErrorCode.NotFound);
}
if (entity.Authorized("Edit", currentUser))
{
service.Delete(entity);
return ByFormat(true, format);
}
return ByErrorCode(ErrorCode.Forbidden);
}
catch (Exception)
{
return ByErrorCode(ErrorCode.ServerError);
}
}
}
}
using System.Web.Mvc;
public abstract class RestControllerBase : Controller
{
protected enum ErrorCode
{
Unauthenticated = 401,
Forbidden = 403,
NotFound = 404,
ServerError = 500
}
protected ActionResult ByFormat(object returnedObj, string dataFormat)
{
if (!string.IsNullOrEmpty(dataFormat) && dataFormat.ToLower() == "xml")
{
return new XmlResult(returnedObj);
}
return Json(returnedObj);
}
protected ActionResult ByErrorCode(ErrorCode errorCode)
{
switch(errorCode)
{
case ErrorCode.Unauthenticated:
return HttpStatusCode(401);
case ErrorCode.Forbidden:
return HttpStatusCode(403);
case ErrorCode.NotFound:
return HttpNotFound();
case ErrorCode.ServerError:
default:
return HttpStatusCode(500);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using Rock.Models.Core;
using Rock.Models.Crm;
using Rock.Repository.Crm;
using Rock.Services;
using Rock.Services.Core;
namespace Rock.Framework.Services.Crm
{
/// <summary>
/// Business object to handle abstraction of access to entities and repository layer.
/// </summary>
public class TestPersonService : Service, IEntityService<Person>
{
private readonly IPersonRepository _repository;
public TestPersonService() : this(new EntityPersonRepository())
{ }
public TestPersonService(IPersonRepository PersonRepository)
{
_repository = PersonRepository;
}
public IQueryable<Person> Queryable()
{
return _repository.AsQueryable();
}
public Person GetByID(int id)
{
return _repository.FirstOrDefault(p => p.Id == id);
}
public Person GetByGuid(Guid guid)
{
return _repository.FirstOrDefault(p => p.Guid == guid);
}
public void Attach(Person entity)
{
_repository.Attach(entity);
}
public void Add(Person entity)
{
_repository.Add(entity);
}
public void Delete(Person entity)
{
_repository.Delete(entity);
}
public void Save(Person entity, int? id)
{
List<EntityChange> entityChanges = _repository.Save(entity, id);
if (entityChanges != null)
{
EntityChangeService entityChangeService = new EntityChangeService();
foreach (EntityChange entityChange in entityChanges)
{
entityChange.EntityId = entity.Id;
entityChangeService.AddEntityChange(entityChange);
entityChangeService.Save(entityChange, id);
}
}
}
}
}
@JasonOffutt
Copy link
Author

That's a very good point. We could make all these controllers partial classes, just like we discussed with the WCF implementation to tack on custom functionality on the fly.

The default implementation could just cover basic CRUD, and we could add the extra icing as needed (e.g. - find by email, etc).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment