4

If my action has a path like /controller/action/{id} I can get id in an AuthorizeAttribute by doing httpContext.Request.RequestContext.RouteData.Values["id"].

Conversely, if it's something like /controller/action?id={id} I can get it by doing httpContext.Request.QueryString["id"].

I'll need yet another way if it's form data from a POST.

Is there a way to say "Get what you would put in the parameter with name 'id', regardless of how the route is specified?"

Xodarap
  • 11,581
  • 11
  • 56
  • 94
  • @Xodarap Just out of curiousity, why do you need this in an action filter such as an `AuthorizeAttribute`? – bzlm Mar 07 '11 at 21:43
  • @bzlm: e.g. I want to verify that someone is editing a post which they authored. (So I need the post ID). – Xodarap Mar 07 '11 at 21:46
  • @Xodarap Saw your related question. This is a very atypical task for an action filter, since filters are by design oblivious to the details of the action (including the parameters). This would normally be implemented inside the actual actions that need authorization, why not do that? Also, if your filter determines you are not the author, what should it do? Redirect? Return a view? Is that really the job for an action filter? – bzlm Mar 07 '11 at 21:51
  • @bzlm: consider SO. I might mod a certain tag but not others, so I'd need tag-specific security. Shouldn't this be handled by some attribute? There are many actions which might need this security check and wrapping everything in a `if(check){ ... } else { redirect }` seems pointless. – Xodarap Mar 07 '11 at 21:58
  • 2
    @bzlm: Doing authentication in an action [is *broken* if caching is used.](http://blogs.teamb.com/craigstuntz/2009/09/09/38390/) Actions don't even run when the results are cached! Yes, it *is* a job for an action filter, which is why the MVC framework designers chose to put it in `AuthorizeAttribute` rather than `Controller`. – Craig Stuntz Mar 07 '11 at 22:05
  • 1
    @Xodarap: `httpContext.Request["Id"]` will get the object from Cookies, Form, QueryString or ServerVariables. – CD.. Mar 07 '11 at 22:21
  • @CD: Thanks! If you put this as an answer I'll accept it. – Xodarap Mar 07 '11 at 22:38

1 Answers1

8
var id = Request.RequestContext.RouteData.Values["id"] ?? Request.Params["id"] as string;

or if you want to privilege GET and POST parameters in favor of route data:

var id = Request.Params["id"] ?? Request.RequestContext.RouteData.Values["id"] as string;
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928