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 AuthorizeAttribute 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.
Asked
Active
Viewed 6,855 times
1 Answers
16
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
.

Community
- 1
- 1

David Ruttka
- 14,269
- 2
- 44
- 39
-
Hmm... when I added a Constructor to my Controller to set this variable it broke all of my Model Binding (throws an error). Any other ideas? – MetaGuru Jul 13 '11 at 18:40
-
@Ryan I originally had this noted in my answer but removed it. Perhaps I should put it back in. Anyway, a Controller's constructor fires **before** OnAuthorization, so the item won't be set yet. Furthermore, the Controller doesn't even have an HttpContext yet at that point. You need to do this in your Action. – David Ruttka Jul 13 '11 at 18:42
-
@Ryan An alternative would be to create `OAuthController : Controller`, have it override `OnAuthorization` as mentioned in the post I linked to, have it set a `protected` member, and have your other controllers inherit from it. – David Ruttka Jul 13 '11 at 18:51
-
thank you I forgot about that, in fact couldn't I roll my own OnActionExecuting for the Controller as well? – MetaGuru Jul 13 '11 at 19:11
-
@Ryan No problem, and absolutely. – David Ruttka Jul 13 '11 at 19:16
-
how to do it in asp.net webapi 2? – Neo Jul 18 '17 at 08:49