43

Is there a way to get the full url of a RestSharp request including its resource and querystring parameters?

I.E for this request:

RestClient client = new RestClient("http://www.some_domain.com");
RestRequest request = new RestRequest("some/resource", Method.GET);
request.AddParameter("some_param_name", "some_param_value", ParameterType.QueryString);

IRestResponse<ResponseData> response = client.Execute<ResponseData>(request);

I would like to get the full request URL:

http://www.some_domain.com/some/resource?some_param_name=some_param_value
Jaqen H'ghar
  • 16,186
  • 8
  • 49
  • 52

2 Answers2

88

To get the full URL use RestClient.BuildUri()

Specifically, in this example use client.BuildUri(request):

RestClient client = new RestClient("http://www.some_domain.com");
RestRequest request = new RestRequest("some/resource", Method.GET);
request.AddParameter("some_param_name", "some_param_value", ParameterType.QueryString);

IRestResponse<ResponseData> response = client.Execute<ResponseData>(request);

var fullUrl = client.BuildUri(request);
Jaqen H'ghar
  • 16,186
  • 8
  • 49
  • 52
  • 8
    This is great but I note that in my experience, you can call `BuildUri()` before `Execute()` which seems more natural (I want to log what I'm about to do, not what I just did). – Chris Nelson Dec 29 '17 at 21:22
1

Well, it is pretty tricky. To get the full requested URL use RestClient.Execute(request).ResponseUri to be sure it is the already sent request.

In this example:

RestClient client = new RestClient("http://www.some_domain.com");
RestRequest request = new RestRequest("some/resource", Method.GET);
request.AddParameter("some_param_name", "some_param_value", ParameterType.QueryString);

IRestResponse<ResponseData> response = client.Execute<ResponseData>(request);
Uri fullUrl = response.ResponseUri;

This code:

Console.WriteLine(string.Format("response URI: {0}", response.ResponseUri.ToString()));

returns:

response URI: http://www.some_domain.com/some/resource?some_param_name=some_param_value
Petr Krampl
  • 816
  • 9
  • 11
  • In my application response.ResponseUri only contains the base uri without adding all the parameters – Till Nov 05 '19 at 08:56
  • 1
    This isn't the request Uri, it is the response Uri (per the documentation: "The URL that actually responded to the content (different from request if redirected)") – Rogala Sep 25 '20 at 13:08
  • @Rogala: yes, you are right. In case of redirection, you can use ``string request_url = $"{client.BaseUrl}/{response.Request.Resource}"``, but you do not get the parameters. – Petr Krampl Sep 25 '20 at 14:26
  • @PetrKrampl I could be wrong, but that doesn't take the query parameters into account. If you have access to the client (assuming not in an extension method), then the appropriate answer is the other answer which is `client.BuildUri(request);` – Rogala Sep 25 '20 at 20:28