40

How do I get the complete request URL (including query string) in my controller? Is it a matter of concatenating my URL and form parameters or is there a better way.

I checked this question, but it seems not to be applicable to MVC.

Correct me if I'm wrong.

Some more detailed information:

My call to my SearchController.AdvancedSearch() originates from a form with about 15 optional parameters. Because of the number of parameters and no possible way (I think) to have optional parameters passed in a clean way, I went for a catchall string that is handled in the controller.

Now I want my controller to store its call in a breadcrumb component so that when the crumb is clicked the exact same result can be fetched (with all, but not more, of the arguments included). To do this I need the entire request.URL, including the querystring.

In Request.RawURL, request.URL etc this query string is not included. In fact currently I do a plain function.

String.Format("{0}/{1}", request.Url, request.form)

This gives me some weird results (like submit button values etc), but it works. If there are suggestions on how to make this less of an ugly hack, please do tell.

I know where to find the current request, but I can't seem to find a raw URL anywhere though. They are all deprived from the querystring and I need that bit too.

My controller updates a collection of URLs in my BreadCrumb component. Therefore it needs the request URL. How do you suggest I take on this problem?

Community
  • 1
  • 1
Boris Callens
  • 90,659
  • 85
  • 207
  • 305

5 Answers5

53

You can use Request.Url.PathAndQuery.

MVC5: use Request.RequestUri.PathAndQuery

Apex ND
  • 440
  • 5
  • 12
Serhiy
  • 4,357
  • 5
  • 37
  • 53
  • 2
    Heh, thanks for your answer although this question is like 2 years old ;) In the mean time two more versions of MVC have come out and optional parameters are beter suported by the MVC framework, rendering the problem moot. – Boris Callens Jul 04 '11 at 07:51
25
HttpContext.Current.Request.RawUrl
HttpContext.Current.Request.QueryString

As far as your second question. Instead of tracking the url's, query string info, etc, that your user has gone to. Track the controllers and actions called. That would remove the need for the Request object entirely.

H. Pauwelyn
  • 13,575
  • 26
  • 81
  • 144
Jeff Sheldon
  • 2,074
  • 1
  • 14
  • 23
3
Request.RawUrl

Use this property is return the all url.

Dino Liu
  • 500
  • 4
  • 17
2

You can get at the current Request object by using:

HttpContext.Current.Request

However, I've gotta ask -- why do you want the request URL? By doing this, you've made your controller dependent on the Request object, which will make your unit tests much harder to write.

Roger Lipscombe
  • 89,048
  • 55
  • 235
  • 380
0

Within the controller, you can access Request.RawUrl.

Haacked
  • 58,045
  • 14
  • 90
  • 114