Right now I'm thinking about a pattern to have the 'current user' as a modelbinded parameter in my actions.
My actions would look something like this:
public JsonResult ListStuff(User currentUser, string paramter1, int parameter2)
{
}
And I have a very simple ModelBinder that looks like this:
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
if ( bindingContext.ModelName == "currentUser" )
return Globals.HttpContextItems.User;
return null;
}
I really like that the action is less dependent on another Controller Property. It makes it more clear what the 'input parameters' of the functions are, it's more reusable, and will make it a bit more easily testable in the future.
I'm a bit affraid of security issues though. I probably have to make very sure (i.e. in the DefaultModelBinder) that the currentUser will never be automatically bound by other ModelBinders.
Can anyone shine a light if this might be a good pattern, and if there is stuff that I'm not thinking about at the moment, but that will give problems in the future.
If you are concerned that other ModelBinders will set that parameter, why not create an ActionFilterAttribute so that you'll explicitly have to decorate your action method:
public class GetCurrentUserAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
filterContext.ActionParameters["currentUser"] = filterContext.HttpContext.User;
}
}
Then to use it:
[GetCurrentUser]
public ActionResult Index(User currentUser)
{
}
Definitely not as clean as the default model binder, but a lot more explicit.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With