开发者

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:

  1. A Controller's constructor fires before OnAuthorization, so the item will not yet be set.
  2. The HttpContext is not yet set in the Controller's constructor.

Alternative solution

  1. Create a new OAuthController : Controller
  2. Override OnAuthorization
  3. Move the logic from your filter into OAuthController.OnAuthorization
  4. Set a protected field (i.e., protected object myAuthData) in OAuthController
  5. Have your other controllers inherit from OAuthController instead of Controller
  6. Your other controllers can access myAuthData.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜