Error showing while using RestSharp RestClient method - c#

My API is calling REST API using RestSharp and Code looks like this
var runRequest = { Contains my JSON}
var client = new RestClient(".....");
var request = new RestRequest("....", Method.Post);
string AuthHeader = "...";
request.AddParameter("application/json", runRequest, ParameterType.RequestBody);
request.AddParameter("Authorization", "Bearer " + AuthHeader, ParameterType.HttpHeader);
var response = client.Execute(request); <---- {Red line showing under client}
return Ok(response);
Error
Because of that red line, I am not able to run my program. Can somebody please tell what the issue can be ?
Thank you

You are using the latest RestSharp version. All the sync methods were deprecated as RestSharp uses HttpClient under the hood, and HttpClient doesn't have any sync overloads, everything is async.
You can find a list of changed or deprecated members of RestClient in the documentation.

Related

Why post Body is sometimes null using WSO2 Api Manager and .Net

I'm testing WSO2 Api Manager.
I have some Apis working good and wow I need to integrate them with Api Manager 2.6.0. I've make some test and all Get requests work very good, but when I make Post Request sometimes failed. For some reason the parameters from body are nulls, another times the parameters are received by the APIs.
However if I make the requests without Api Manager, they all work good all the time.
My APIs are developed in .Net Web Api 2.0.
This is my code to call APIs, I make some test with HttpClient and RestSharp getting the same result. However when I test using Postman, the APIS always work good, event through the API Manager.
Example using HttpClient:
public async Task PostHttpClient(TarificacionParametros entidad, string url)
{
var personaJson = JsonConvert.SerializeObject(entidad);
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Accept.Clear();
//httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", BEARER);
HttpContent httpContent = new StringContent(personaJson, System.Text.Encoding.UTF8, "application/json");
HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;
if (response.IsSuccessStatusCode)
{
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
var data = JsonConvert.DeserializeObject<object>(responseBody);
}
}
Example using Restsharp:
public async Task PostRestSharp(TarificacionParametros entidad, string url)
{
var client = new RestClient(url);
var request = new RestRequest(Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddJsonBody(entidad);
Console.WriteLine(entidad.Capital);
// easily add HTTP Headers
request.AddParameter("Authorization", "Bearer " + BEARER, ParameterType.HttpHeader);
var response = client.Execute<object>(request);
}
Note: I don't post API's code because they are good, they have time working with any problem in production, now we just need to integrate them with WSO2 Api Manager.
Regards

RestSharp "Not found" response

I'm trying to use the Youtube Data API v3 with RestSharp. Problem is: I get the response: "Not found" when I try to send a request.
var client = new RestClient("https://www.googleapis.com/youtube/v3/channels?part=statistics");
var request = new RestRequest(Method.POST);
request.AddParameter("key", my api key);
request.AddParameter("id", my channel id);
request.AddParameter("fields", "items/statistics/subscriberCount");
IRestResponse response = client.Execute(request);
var content = response.Content;
Console.WriteLine(response.Content);
this.BeginInvoke((System.Windows.Forms.MethodInvoker)delegate () { label1.Text = response.Content; });
This seems to be a problem with RestSharp or the code because in the Google API explorer thing you can test out the inputs and it works there.
I was trying the same thing today and was stuck on the same step. With an hour of effort I figured out.
In the RestClient(baseUri) constructor, just pass the base url and not the whole path.
While initializing RestClient(resource, Method), pass the path as resource and method will be the second parameter.

ExecuteAsyncPost Example in RestSharp.NetCore

I'm working with RestSharp.NetCore package and have a need to call the ExecuteAsyncPost method. I'm struggling with the understanding the callback parameter.
var client = new RestClient("url");
request.AddParameter("application/json", "{myobject}", ParameterType.RequestBody);
client.ExecuteAsyncPost(request,**callback**, "POST");
The callback is of type Action<IRestResponse,RestRequestAsyncHandler>
Would someone please post a small code example showing how to use the callback parameter with an explanation.
Thanks
-C
This worked for me using ExecuteAsync for a Get call. It should hopefully point you in the right direction. Note that the code and credit goes to https://www.learnhowtoprogram.com/net/apis-67c53b46-d070-4d2a-a264-cf23ee1d76d0/apis-with-mvc
public void ApiTest()
{
var client = new RestClient("url");
var request = new RestRequest(Method.GET);
var response = new RestResponse();
Task.Run(async () =>
{
response = await GetResponseContentAsync(client, request) as RestResponse;
}).Wait();
var jsonResponse = JsonConvert.DeserializeObject<JObject>(response.Content);
}
public static Task<IRestResponse> GetResponseContentAsync(RestClient theClient, RestRequest theRequest)
{
var tcs = new TaskCompletionSource<IRestResponse>();
theClient.ExecuteAsync(theRequest, response => {
tcs.SetResult(response);
});
return tcs.Task;
}
RestSharp v106 support .NET Standard 2.0 so if your code worked with RestSharp 105 under .NET Framework - it will also work with .NET Core 2.
RestSharp.NetCore package is not from RestSharp team and is not supported by us. It is also not being updated and the owner does not respond on messages, neither the source code of the package is published.

How to make REST GET in Asp.net C#?

I can get an access token of Office 365. I can not make a REST request (GET) attaching this token in the header.
I'm using this code:
RestClient client = new RestClient();
client.EndPoint = #"https://outlook.office365.com/api/v1.0/me/folders/inbox/messages?$top=10";
client.Method = HttpVerb.GET;
client.ContentType = "application/json";
client.PostData = "authorization: Bearer " + myAccesToken.ToString();
String json = client.MakeRequest();
I've tested the access token in http://jwt.calebb.net and it's ok.
But it's always returning:
The remote server returned an error: (400) Bad Request.
I'm kind a knewby to REST and my english is not that good... Sorry! :)
(RE)EDIT
I've tried with RestSharp and I've simplified a bit my code...
Now I'm using my access token to make the GET request.
How do I add the "authorization bearer" to my request?
Is it like this?
//Ask for the token
var client = new RestClient("https://login.windows.net/common/oauth2/token");
var request = new RestRequest(Method.POST);
request.AddParameter("grant_type", "authorization_code");
request.AddParameter("code", Request.QueryString["code"]);
request.AddParameter("redirect_uri", myRedirectUri);
request.AddParameter("client_id", myClientID);
request.AddParameter("client_secret", myClientSecret);
IRestResponse response = client.Execute(request);
string content = "[" + response.Content + "]";
DataTable dadosToken = (DataTable)JsonConvert.DeserializeObject<DataTable>(content);
//I don't need a DataTable, but it was a way to retrieve my access token... :)
//Ask for info with the access token
var client2 = new RestClient("https://outlook.office365.com/api/v1.0/me");
var request2 = new RestRequest(Method.GET);
request2.AddHeader("authorization", myToken.ToString());
//I've tried this way also:
//client2.Authenticator = new OAuth2AuthorizationRequestHeaderAuthenticator(dadosToken.Rows[0]["access_token"].ToString(), "Bearer");
IRestResponse response2 = client2.Execute(request2);
string content2 = "[" + response2.Content + "]";
Response.Write(content2); //this returns NOTHING!
Thanks again!
You can also use Fiddler to figure out if the Request is well formed.
Try a simpler endpoint first like: https://outlook.office365.com/api/v1.0/me
and check if the right data comes back. You can call this endpoint just from the browser and also look at the request/respond inside Fiddler.
The first thing to check: Is it a bad request. This usually means the method can't be found or the given parameters cannot be located. Check the deploy and make sure it is the most up to date version and also check that your server is actually running.

Restsharp PUT custom header

I have to use RestSharp to PUT some data into an API.
The API resource is: /clients/services/finances/{finances-id}/subcategory/{subcategory-id}
Apart from template parameters, there are some query parameters:
organization-id (string)
operator-id (string)
And also, the request Content-Type must be application/xml
The way I'm trying to create this PUT request using RestSharp:
RestClient client = new RestClient(url);
client.Authenticator = Auth1Authenticator.ForRequestToken(Config.getVal("api_key"), Config.getVal("secret_key"));
IRestRequest request = new RestRequest("", Method.PUT);
request.RequestFormat = DataFormat.Xml;
request.AddParameter("organization-id", Config.getVal("params.org"));
request.AddParameter("operator-id", "Accounting");
IRestResponse response = client.Execute(request);
But I'm only get HTTP Status 415 - Unsupported Media Type
Can you please help me to resolve this. GET request is working like a charm.
Try sending your request body like this:
request.XmlSerializer = new RestSharp.Serializers.XmlSerializer();
request.RequestFormat = DataFormat.Xml;
request.AddBody([new instance of the object you want to send]);
Also, are you sure that the URL you're accessing is correct (i.e. have the placeholders been filled with your params)?
Alternatively you can try doing this:
request.AddParameter("text/xml", [your object to serialize to xml], ParameterType.RequestBody);
You might also try and make your example as similar to the restsharp wiki example as possible to make it work:
https://github.com/restsharp/RestSharp/wiki/Recommended-Usage

Categories

Resources