Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

currentUser as a modelbinded parameter

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.

like image 673
Dirk Boer Avatar asked Nov 17 '25 14:11

Dirk Boer


1 Answers

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.

like image 73
Cloud SME Avatar answered Nov 19 '25 10:11

Cloud SME



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!