17
[ApiBasicAuthorize]
public ActionResult SignIn()
{

}

I have this custom filter called ApiBasicAuthorize. Is it possible to access ApiBasicAuthorize's data (properties etc) inside the controller action SignIn?

If not, how do I pass data from the filter to controller action?

Shekhar Pankaj
  • 9,065
  • 3
  • 28
  • 46
Gautam Jain
  • 6,789
  • 10
  • 48
  • 67

2 Answers2

26

There is a dictionary called items attached to the HttpContext object. Use this dictionary to store items shared across components during a request.

public override void OnAuthorization(AuthorizationContext filterContext)
{
    filterContext.HttpContext.Items["key"] = "Save it for later";

    base.OnAuthorization(filterContext);
}

Then anywhere in your code later in the request...

var value = HttpContext.Current.Items["key"];
Jeremy Bell
  • 2,104
  • 1
  • 14
  • 9
  • 1
    Even Praveen's answer works, but I have marked this as an answer because HttpContext.Items is more appropriate for this purpose instead of RouteData.Values – Gautam Jain Aug 16 '11 at 07:23
  • 2
    @goths - Hi, could you please explain why you chose `HttpContext.Items` over `RouteData`? Also see: http://stackoverflow.com/a/1809541/538387 Thanks – Tohid Dec 26 '12 at 17:15
  • Hi @goths, yes I also am curious why the former is more "appropriate" than the latter? It seems like they're both serving the same purpose, so wondering what limitations or intentions separate the two? – Funka Mar 07 '13 at 02:32
  • Question. Is the HttpContext.Items value is threadsafe. is If I use the Custom Filter attribute in multiple actions and call it at the same time, how do we make sure the the right controller action will get the right data? – SRAMPI Jul 20 '18 at 20:13
6
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        var rd = filterContext.RouteData;

        //add data to route
        rd.Values["key"]="Hello";

        base.OnAuthorization(filterContext);
    }



public ActionResult(string key)
{
 //key= Hello
return View();
}
Praveen Prasad
  • 31,561
  • 18
  • 73
  • 106