RestSharp get full URL of a request - c#

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

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);

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

Related

Restsharp Request gives "Argument 1: cannot convert from 'RestSharp.Method' to 'string?'" error

I am trying to call POST API request using restSharp 108.0.1v.
The code is as below;
var client = new RestClient("https://driver-vehicle-licensing.api.gov.uk/vehicle-enquiry/v1/vehicles");
var request = new RestRequest(Method.Post);
request.AddHeader("x-api-key", "MYAPIKEY");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n\t\"registrationNumber\":\"AA19AAA\"\n}", ParameterType.RequestBody);
RestResponse response = client.Execute(request);
The snippet Method.Post of var request = new RestRequest(Method.Post);gives the error that I mentioned.
Please help me to solve this issue ?
Looking at the documentation here the first parameter of the RestRequest constructor is the subpath to the resource you want to access. Instead you should do something like the following
var client = new RestClient("https://driver-vehicle-licensing.api.gov.uk");
var request = new RestRequest("vehicle-enquiry/v1/vehicles", Method.Post);
// ... or I believe this should work as well:
var client = new RestClient("https://driver-vehicle-licensing.api.gov.uk/vehicle-enquiry/v1");
var request = new RestRequest("vehicles", Method.Post);

Example of OAuth authenticated request using .NET framework

The Node.JS code below sends 0-legged OAuth authenticated request to the API:
'use strict';
var OAuth = require('OAuth');
var express = require('express');
var app = express();
var oauth = new OAuth.OAuth(
'http://example.com/oauth/request_token',
'http://example.com/oauth/access_token',
'mykey',
'none',
'1.0',
null,
'HMAC-SHA1'
);
app.get('/', function (req, res) {
oauth.get(
'http://example.com/api',
'token123',
'tokensecret123',
function (error, data, response){
data = JSON.parse(data);
res.json(data);
});
});
I need to convert this code to C# or VB.NET. Any sample of OAuth authenticated request in .Net will help too.
I do it with the library RestSharp which helps to deal with REST API.
The code below send a request to get a token from the OAuth:
var restClient = new RestClient();
restClient.BaseUrl = new Uri("theApiBaseUrl");
string encodedCredentials = Convert.ToBase64String(Encoding.Default.GetBytes($"yourAppId:yourSecret"));
// change the request below per the API requirement
RestRequest request = new RestRequest("theApiUrlForAuthentication", Method.POST);
request.AddHeader("Accept", "application/json");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddHeader("Authorization", $"Basic {encodedCredentials}");
request.AddQueryParameter("grant_type", "client_credentials");
request.AddQueryParameter("scope", "api");
IRestResponse response = restClient.Execute(request);
// the token should be in the JSON string response.Content
// now you'll want to deserialize the JSON to get the token
var jsonWithToken = MyFunctionToGetToken(response.Content);
Now you have the token in order to do authenticated calls to the API:
var restClient = new RestClient();
restClient.BaseUrl = new Uri("theApiBaseUrl");
RestRequest request = new RestRequest("theApiEndpoint", Method.GET);
request.AddHeader("Accept", "application/hal+json");
request.AddHeader("profile", "https://api.slimpay.net/alps/v1");
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Authorization", $"Bearer {token}");
RestClient.Execute(request);
Each API is different, so you'll surely have to modify my code (add or remove headers, encoding the credentials, ...) so that it works for you.
Thank you #Guillaume Sasdy for steering me towards RestSharp. Here is a working solution that works the same way as the node.js code in my question.
Since API I'm accessing is using 0-legged OAuth, the Access Token and Access Secret are known upfront and make things much easier.
const string consumerKey = "mykey";
const string consumerSecret = "none";
var baseUrl = "https://example.com";
var client = new RestClient(baseUrl);
var request = new RestRequest("/api");
client.Authenticator = OAuth1Authenticator.ForProtectedResource(
consumerKey, consumerSecret, "token123", "tokensecret123"
);
var response = client.Execute(request);

How to open my GET RestRequest in URL to login

My problem is for oath2 first auth for client approval (then redirected to a callback url which handle token exchange)
I need to add acr_value to a DotNetOpenAuth client.RequestUserAuthorization process. Can't find a method of doing this so I created the request in Restsharp instead but my Restsharp GET do not redirect user to URL stated in the request. Pls help.
Below is working code in a http post:
(Takes me to server, sign-approval, back to callback)**
DotNetOpenAuth.OAuth2.WebServerClient client = authclass.CreateClient();
client.RequestUserAuthorization(scopes, redirectUri);
return View();
Below is a working request but aren't taking user to URL in GET
public ActionResult XXXXX (object sender, EventArgs e)
string apiServerHost =
WebConfigurationManager.AppSettings["AuthServerHost"];
var path = string.Format("connect/authorize");
string client_id = WebConfigurationManager.AppSettings["ClientId"];
string client_secret =
WebConfigurationManager.AppSettings["ClientSecret"];
string redirect_uri = WebConfigurationManager.AppSettings["RedirectUri"];
var client = new RestClient(apiServerHost);
client.Authenticator = new HttpBasicAuthenticator(client_id,
client_secret);
var request = new RestRequest(path, Method.GET);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("redirect_uri", redirect_uri);
request.AddHeader("scope", "XXXXXXXXX");
request.AddHeader("promt", "login");
request.AddHeader("acr_values", "XXXXXXXXXXX");
IRestResponse response = client.Execute(request);
return View("XXXX");

Restsharp returns 403 while Postman returns 200

This is the (modified) snippet that Postman gives for successful call to my page.
var client = new RestClient("http://sub.example.com/wp-json/wp/v2/users/me");
var request = new RestRequest(Method.GET);
request.AddHeader("authorization", "Basic anVyYTp3MmZacmo2eGtBOHJsRWrt");
IRestResponse response = client.Execute(request);
But when placed in my c# app it returns 403 forbidden, while Postman makes it and recieves 200.
The same thing happens when I use httpclient in my app (403).
Use RestClient.Authenticator instead:
var client = new RestClient("http://sub.example.com/wp-json/wp/v2/users/me")
{
Authenticator = new HttpBasicAuthenticator("User", "Pass")
};
var request = new RestRequest(Method.GET);
IRestResponse response = client.Execute(request);
Edit:
Since the issue (as mentioned in the comments) is the fact that RestSharp doesn't flow the authentication through redirects, I'd suggest going with a combination of HttpClient with a HttpClientHandler where you set the authentication to flow.
[Solution]
Use the below line for the header
Headers.Add("User-Agent: Other");

How to use RestSharp for non standard url containing symbols like = and ::?

I have to call the following URL using RestSharp.
Some part of the uri are not standard.
How can I get to use them in
The url is the following but without the white space:
http:// mysite.com/api/v2.php?method = information :: method&token=b&target_id=0
I've tried something like this but RestSharp is not calling the URL I was expecting to call.
var client2 = new RestClient("http:// mysite.com/api/v2.php");
var request = new RestRequest("method=information::method", Method.GET);
request.AddParameter("token", authenticationToken);
request.AddParameter("target_id", targetId);
You don't mention what url your code actually calls, but I guess that your method is parsed as a file/path, and not a parameter.
var client = new RestClient("http:// mysite.com/api/");
var request = new RestRequest("v2.php", Method.GET);
request.AddParameter("method", "information::method");
request.AddParameter("token", authenticationToken);
request.AddParameter("target_id", targetId);

Categories