How can I pass data from an AuthorizeAttribute to the Controller?
I have created a custom AuthorizeAttribute which verifies some OAuth credentials that are sent inside the HTTP header. I am using some of these credentials to identify who is making the request. Once I parse this information in the AuthorizeA开发者_如何学编程ttribute is there any way to pass it over so that the data can be assigned to an instance variable of the Controller? Then anywhere in my Controller I will have the ID of the requesting party.
Original answer
You should be able to do this in your filter
filterContext.HttpContext.Items["test"] = "foo";
And then this in your action
_yourVariable = HttpContext.Items["test"];
You'd probably want to use a more unique key than "test"
, but that's the idea.
EDIT There are two reasons we do this in the action rather than the constructor:
- A Controller's constructor fires before OnAuthorization, so the item will not yet be set.
- The HttpContext is not yet set in the Controller's constructor.
Alternative solution
- Create a new
OAuthController : Controller
- Override
OnAuthorization
- Move the logic from your filter into
OAuthController.OnAuthorization
- Set a
protected
field (i.e.,protected object myAuthData
) inOAuthController
- Have your other controllers inherit from
OAuthController
instead ofController
- Your other controllers can access
myAuthData
.
精彩评论