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");
Related
At the moment I am using the following RestSharp request to get a website's content:
var client = new RestClient(productLink);
var request = new RestRequest(Method.GET);
request.AddHeader("Cookie", "insert-cookie-content");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
I have tried converting it into HttpClient as i will need to use the AllowRedirect property later:
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Add("Cookie", "insert-cookie-content");
var response = await client.GetAsync(productUrl);
Console.WriteLine(response);
The URL I am trying to get a response from is: https://www.nike.com/sg/launch/t/air-max-90-orange-duck-camo
My first problem is that the HttpClient request is giving me 403 Errors whereas the RestClient request was working fine. How can I fix this?
My second problem is that the cookie expires after a couple of uses, and I have to manually get a new one from postman and insert it. Is there anyway for the request to generate its own cookie?
Here is the two fiddler responses compared: https://imgur.com/a/bZo7d9F
In case of HttpClient if you want to pass the Cookies manually through the DefaultRequestHeaders then you have to tell this to the HttpClient to do NOT use CookieContainer. You have to use HttpClientHandler's UseCookie flag to indicate it.
var client = new HttpClient(new HttpClientHandler { UseCookies = false });
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Add("Cookie", "insert-cookie-content");
var response = await client.GetAsync(productUrl);
Console.WriteLine(response);
I have this piece of code to upload a file to a server:
var client = new RestClient("http://localhost:8888/add");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddFile("image", "E:/1.jpg");
request.AddParameter("filepath", "images_store/1");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
This code is generated by Postman itself but when I run it in my app it give BadRequest
Whats wrong?
I see in postman you selected form-data as ContentType, but in code it says x-www-form-urlencoded.
Habe you tried changing that?
Credentials are right, because I can get an API response using PS with the same client id and secret. The token isn't invalid, but it won't get attached correctly to the rest request
Unauthorized. Access token is missing or invalid
Here's my code:
var client = new RestClient(url);
client.Authenticator = new OAuth2AuthorizationRequestHeaderAuthenticator("Bearer: " + OAuthToken);
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddHeader("Accept", "application/json");
foreach (var paramName in parameters.Keys) {
request.AddParameter(paramName, parameters[paramName]);
}
request.RequestFormat = DataFormat.Json;
IRestResponse response = client.Execute(request);
if (response.StatusCode == HttpStatusCode.OK) {
string rawResponse = response.Content;
dynamic deserializedResponse = new JsonDeserializer().Deserialize<dynamic>(response);
return deserializedResponse;
}
else {
Dictionary<string, string> returnData = new JsonDeserializer().Deserialize<Dictionary<string, string>>(response);
throw new Exception("Failed call to API Management: " + string.Join(";", returnData));
}
I've also tried using:
request.AddHeader("authorization", "Bearer " + OAuthToken);
request.AddHeader("authorization", string.Format("Bearer " + OAuthToken));
request.AddHeader("authorization", string.Format("Bearer: " + OAuthToken));
request.AddHeader("authorization", $"Bearer {OAuthToken}");
request.AddParameter("authorization, "Bearer " + OAuthToken", HttpRequestHeader);
request.AddHeader("authorization", "bearer:" + access + "");
None worked.
Following code worked for me:
var restClient = new RestClient(Url)
{
Authenticator = new OAuth2AuthorizationRequestHeaderAuthenticator(accessToken, "Bearer")
};
As a result, the "Authorization" header will contain "Bearer {accessToken}"
I was not able to authenticate when I was using it like
request.AddHeader("Authorization", $"Bearer {axcessToken}");
instead this worked for me
client.AddDefaultHeader("Authorization", $"Bearer {axcessToken}");
You don't need the Authenticator.
First, you should decorate the controller or the action like below:
[Authorize(AuthenticationSchemes = "Bearer")]
public class ApiServiceController : Controller
{
}
or better than that:
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
public class ApiServiceController : Controller
{
}
Then you should add token bearer as this line:
request.AddParameter("Authorization", $"Bearer {OAuthToken}", ParameterType.HttpHeader);
where OAuthToken is the value of the received token from login.
If you need more codes, just tell me ;)
Question is old but for any one coming to this again.. this is what worked for me:
My project was configured to use Https, and I was not sending an Https request so server was sending me back a response informing that I should be using a Https request instead. After that, RestSharp performs automatically a redirect using Https this time, but is not including the Authorization Header. Mor infor here: https://github.com/restsharp/RestSharp/issues/414
My solutions was just to change my web api Url to use Https
https://.../api/values
Not sure if this will help anyone, but in my case the problem was JWT issue time. I was using current time, and the server was a few seconds behind. I noticed that the JWT token was working when I was stepping through the code, but not when I was running it without pausing. I fixed the problem by subtracting 1 minute from JWT issue time.
Use
var client = new RestClient(URL);
client.AddDefaultHeader("Authorization", string.Format("Bearer {0}", accessToken));
I had the same issue in ASP.NET Framework. Using the AddParameter, as below, worked.
RestClient client = new RestClient(Url);
RestRequest request = new RestRequest(Method.POST);
request.AddParameter("token", _OsiApiToken);
request.AddParameter("value", value);
IRestResponse response = client.Execute(request);
Prior to the above (working version) I had the Url as...
String.Format("https://myorg.locator.com/arcgis/rest/services/something/?token={0}&value={1}", X, Y)
Strangely the latter String.Format() worked in one project but not in another. Weird.
I went through the OAuth2 proccess in DocuSign API, I follow all the steps using official docs, but when I tried to perform the request in order to get the the AccessToken I received an HTML as response, indicating something like "DocuSign is temporarily unavailable. Please try again momentarily." Although the http response is 200(OK), The weird stuff is when I test with the same values on Postman I get the correct response.
This is my code
public static DocuSignBearerToken GetBearerToken(string AccessCode, bool RefreshToken = false)
{
string AuthHeader = string.Format("{0}:{1}", DocuSignConfig.IntegratorKey, DocuSignConfig.SecretKey);
var client = new RestClient("http://account-d.docusign.com");
client.Authenticator = new HttpBasicAuthenticator(DocuSignConfig.IntegratorKey, DocuSignConfig.SecretKey);
var request = new RestRequest("/oauth/token", Method.POST);
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddHeader("authorization", "Basic " + Base64Encode(AuthHeader));
if(!RefreshToken)
request.AddParameter("application/x-www-form-urlencoded", string.Format("grant_type=authorization_code&code={0}", AccessCode), ParameterType.RequestBody);
else
request.AddParameter("application/x-www-form-urlencoded", string.Format("grant_type=refresh_token&refresh_token={0}", AccessCode), ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
var responseString = response.Content;
DocuSignBearerToken Result = JsonConvert.DeserializeObject<DocuSignBearerToken>(responseString);
return Result;
}
Ok, this is awkward, reading the DocuSign docs they never specify if the authorization URL is http or https I assumed it was http, postman is smart enough to determine http or https when performs the request, my code doesn't, simply changing the Authorization URL from http:// to https:// solves the error.
If your tests using Postman work, then there is a problem with your code.
We've all been there, including me!
In these cases, I send my request to requestb.in to see what I'm really sending to the server. You'll find something is different from what you're sending via Postman.
I want to create/modify an issue on redmine using the PUT/POST methods of restSharp.
I cannot find valuable information about xml PUT/POST using Rest sharp. I tried various methods from restsharp.org like Addbody("test", "subject"); , IRestResponse response = client.Execute(request); but there is no change in Redmine. What am I doing wrong?
POST gives a "Only get, put, and delete requests are allowed." message.
PUT gives a "Only get, post, and delete requests are allowed." message.
My Code
RestClient client = new RestClient(_baseUrl);
client.Authenticator = new HttpBasicAuthenticator(_user, _password);
RestRequest request = new RestRequest("issues/{id}.xml", Method.POST);
request.AddParameter("subject", "Testint POST");
request.AddUrlSegment("id", "5");
var response = client.Execute(request);
The problem was in the serialization. My Issue class contains object of various other classes which was causing a problem in the serialization.
This is how we did it:
RestRequest request = new RestRequest("issues/{id}.xml", Method.PUT);
request.AddParameter("id", ticket.id, ParameterType.UrlSegment);
request.XmlSerializer = new RedmineXmlSerializer();
request.AddBody(ticket);
RestClient client = new RestClient(_baseUrl);
client.Authenticator = new HttpBasicAuthenticator(_user, _password);
IRestResponse response = client.Execute(request);
Your code looks ok to me, I'm unsure if you need this but we added this header when using RestSharp for json against a WebAPI host:
request.AddHeader("Accept", "application/xml");