5

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?"

7
  • @Xodarap Just out of curiousity, why do you need this in an action filter such as an AuthorizeAttribute? Commented Mar 7, 2011 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). Commented Mar 7, 2011 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? Commented Mar 7, 2011 at 21:51
  • 2
    @bzlm: Doing authentication in an action is broken if caching is used. 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. Commented Mar 7, 2011 at 22:05
  • 1
    @Xodarap: httpContext.Request["Id"] will get the object from Cookies, Form, QueryString or ServerVariables. Commented Mar 7, 2011 at 22:21

1 Answer 1

9
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;
Sign up to request clarification or add additional context in comments.

2 Comments

you should enclose into parentesis () var id = (Request.Params["id"] ?? Request.RequestContext.RouteData.Values["id"]) as string;
what if the action method also serves as the childAction and the id is passed as routeValues?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.