Custom IIdentity and passing data from an attribute to a controller

Posted by DM on Stack Overflow See other posts from Stack Overflow or by DM
Published on 2010-04-06T22:36:41Z Indexed on 2010/04/07 3:23 UTC
Read the original article Hit count: 532

Here's my scenario:

I've successfully created a custom IIdentity that I pass to a GenericPrincipal. When I access that IIdentity in my controller I have to cast the IIdentity in order to use the custom properties. example:

public ActionResult Test()
{
    MyCustomIdentity identity = (MyCustomIdentity)User.Identity;
    int userID = identity.UserID;
    ...etc...
}

Since I need to do this casting for nearly every action I would like to wrap this functionality in an ActionFilterAttribute. I can't do it in the controller's constructor because the context isn't initialized yet. My thought would be to have the ActionFilterAttribute populate a private property on the controller that I can use in each action method. example:

public class TestController : Controller
{
    private MyCustomIdentity identity;

    [CastCustomIdentity]
    public ActionResult()
    {
        int userID = identity.UserID;
        ...etc...
    }
}

Question: Is this possible and how? Is there a better solution? I've racked my brain trying to figure out how to pass public properties that are populated in an attribute to the controller and I can't get it.

© Stack Overflow or respective owner

Related posts about asp.net-mvc

Related posts about asp.net-mvc-2