Search code examples
asp.net-mvcasp.net-mvc-3dryservice-layerapplicationcontroller

DRY-ing ASP.NET MVC actions: ApplicationController or Service?


I'm writing an ASP.NET MVC 3 app and I'm finding myself writing this line rather often in my action methods:

var user = _session.Single<User>(u => u.UserName == User.Identity.Name);

(Obviously used in conjunction with the AuthorizeAttribute)

There are other things that get repeated quite often but this one is the most prominent and I end up having 3 actions next to each other, each needing to retrieve the authorized user.

So this needs DRY-ing up:

  1. Should I write an ApplicationContoller from which all other controller inherit and expose a User property there or should I add this to my IAdminService and expose it as a method?

  2. Is an ApplicationController something to avoid or to embrace in ASP.NET MVC?


Solution

  • If you are finding yourself repeating this logic then a custom model binder for the User type might help:

    public class UserModelBinder : DefaultModelBinder
    {
        private readonly ISession _session;
        public UserModelBinder(ISession session)
        {
            _session = session;
        }
    
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var username = controllerContext.HttpContext.User.Identity.Name;
            return _session.Single<User>(u => u.UserName == username);
        }
    }
    

    and once you register the binder your controller action might look like this:

    [Authorize]
    public ActionResult Foo(User user)
    {
        // ...
    }