Good morning, I'm retrieving an authorization token using RestSharp, but instead of returning a Token, it returns an html page:
var client = new RestClient("https://iam.efatura.cv/auth/realms/taxpayers/ protocol/openid- connect/auth"); var request = new RestRequest(Method.POST); request.AddHeader("grant_type", "authorization_code"); request.AddHeader("content-type", "application/x-www-form-urlencoded"); request.AddHeader("accept", "application/json"); request.AddParameter("application/x-www-form-urlencoded", "grant_type=client_credentials&client_id=adadasdasdasdasda& scope=openid&clientSecretasdadsdadasdasdasdasdasdasdasasd& redirect_uri=https://iam.efatura.cv/auth/realms/taxpayers", ParameterType.RequestBody); IRestResponse response = client.Execute(request); Token=response.Content;
Related
I subscribed to Computer Vision API on RapidAPI. When I'm testing the API on the RapidAPI platform, it's working perfectly. But when I'm calling it from my app, it responding 400 Bad request.
How can I fix this problem?
I'm using the RESTSharp library.
Here's my code -
public static IRestResponse GetClassifiedImageData()
{
var client = new RestClient("{Client Path}");
var request = new RestRequest(Method.POST);
request.AddHeader("x-rapidapi-host", "{Rapid API host}");
request.AddHeader("x-rapidapi-key", "{My API key}");
request.AddHeader("content-type", "application/json");
request.AddHeader("accept", "application/json");
request.AddParameter("application/json", "{\"url\":\"Image URL\"}", ParameterType.RequestBody);
return client.Execute(request);
}
And if I call asyncronusly, I get this message -
System.Runtime.CompilerServices.AsyncTaskMethodBuilder1+AsyncStateMachineBox1[System.String,ComputerVision.Program+d__2]
Async Code-
public static async Task<IRestResponse> GetClassifiedImageData2()
{
var client = new RestClient("{Client Path}");
var request = new RestRequest(Method.POST);
request.AddHeader("x-rapidapi-host", "{Rapid API host}");
request.AddHeader("x-rapidapi-key", "{My API key}");
request.AddHeader("content-type", "application/json");
request.AddHeader("accept", "application/json");
request.AddParameter("application/json", "{\"url\":\"Image URL\"}", ParameterType.RequestBody);
return await client.ExecuteAsync(request);
}
I've tried these -
Restarting Visual Studio.
Cleaning Temp and prefetch files.
Based on my test, it is the URL encoding that is causing the problem.
You may use the code sample from Rapid API website. However, while using RestClient, you should not urlencode the urlpath. The Rapid API engineer may make a mistake here. In most case, a , character does not need to be urlencoded. So, you can directly use https://microsoft-azure-microsoft-computer-vision-v1.p.rapidapi.com/analyze?visualfeatures=Categories,Tags,Color,Faces,Description as the path string.
And, anyway, the correct encoded string is https://microsoft-azure-microsoft-computer-vision-v1.p.rapidapi.com/analyze?visualfeatures=Categories%2cTags%2cColor%2cFaces%2cDescription
The code sample from Rapid API:
I used the sample, and got the same error message as yours. But I solved it by using the original string or the correct encoded string:
public static async Task<IRestResponse> GetClassifiedImageDataAsync()
{
// The correct encoded string will work
//var client = new RestClient("https://microsoft-azure-microsoft-computer-vision-v1.p.rapidapi.com/analyze?visualfeatures=Categories%2cTags%2cColor%2cFaces%2cDescription");
// The original string will work
var client = new RestClient("https://microsoft-azure-microsoft-computer-vision-v1.p.rapidapi.com/analyze?visualfeatures=Categories,Tags,Color,Faces,Description");
var request = new RestRequest(Method.POST);
request.AddHeader("x-rapidapi-host", "microsoft-azure-microsoft-computer-vision-v1.p.rapidapi.com");
request.AddHeader("x-rapidapi-key", "71a69********************************3ddb");
request.AddHeader("content-type", "application/json");
request.AddHeader("accept", "application/json");
request.AddParameter("application/json", "{\"url\":\"https://upload.wikimedia.org/wikipedia/commons/1/11/Kanye_West_at_the_2009_Tribeca_Film_Festival.jpg\"}", ParameterType.RequestBody);
return await client.ExecuteAsync(request);
}
static void Main(string[] args)
{
var result = GetClassifiedImageDataAsync().GetAwaiter().GetResult();
Console.WriteLine(result.Content);
}
And you can also use RestClient's method to add query string:
public static async Task<IRestResponse> GetClassifiedImageDataAsync()
{
// Without query string
var client = new RestClient("https://microsoft-azure-microsoft-computer-vision-v1.p.rapidapi.com/analyze");
var request = new RestRequest(Method.POST);
// Add as query string manually
request.AddParameter("visualfeatures", "Categories,Tags,Color,Faces,Description", ParameterType.QueryString);
request.AddHeader("x-rapidapi-host", "microsoft-azure-microsoft-computer-vision-v1.p.rapidapi.com");
request.AddHeader("x-rapidapi-key", "71a69********************************3ddb");
request.AddHeader("content-type", "application/json");
request.AddHeader("accept", "application/json");
request.AddParameter("application/json", "{\"url\":\"https://upload.wikimedia.org/wikipedia/commons/1/11/Kanye_West_at_the_2009_Tribeca_Film_Festival.jpg\"}", ParameterType.RequestBody);
return await client.ExecuteAsync(request);
}
And the successful result:
I am using C# winform on Visual Studio 2019 and using RestSharp.
I have tested WEBAPI function on POSTMAN with correct output.
So i try to implement on C# Winform.
I dump POSTMAN code (C# Restsharp) as following:
var client = new RestClient("http://192.168.2.10:88/en/product/ajax_api_getProductInfoBatch");
var request = new RestRequest(Method.GET);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("Connection", "keep-alive");
request.AddHeader("Content-Length", "21");
request.AddHeader("Accept-Encoding", "gzip, deflate");
request.AddHeader("Host", "192.168.2.10:88");
request.AddHeader("Postman-Token", "f1ff99c7-dc02-40cb-b87a-
a046cf106a96,e2b7d88d-cfc9-4c99-8117-ec48398e56ed");
request.AddHeader("Cache-Control", "no-cache");
request.AddHeader("Accept", "*/*");
request.AddHeader("User-Agent", "PostmanRuntime/7.18.0");
request.AddParameter("undefined", "{\n \"Item No\":\"3101\"\n}",
ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
and i revised
request.AddParameter("undefined", "{\n \"Item No\":\"3101\"\n}"
to
request.AddParameter("application/json", "{\"Item No\":\"3101\"}", ParameterType.RequestBody);
Therefore, the full code will be
private void Button1_Click(object sender, EventArgs e)
{
var client = new RestClient("http://192.168.2.10:88/en/product/ajax_api_getProductInfoBatch");
var request = new RestRequest(Method.GET);
//request.AddHeader("cache-control", "no-cache");
//request.AddHeader("Connection", "keep-alive");
//request.AddHeader("Content-Length", "22");
//request.AddHeader("Accept-Encoding", "gzip, deflate");
//request.AddHeader("Host", "192.168.2.10:88");
//request.AddHeader("Postman-Token", "86e877f8-5755-4e57-960a-eaa78b1e8b6c,da863548-65e0-4053-9cb3-b5760da94165");
//request.AddHeader("Cache-Control", "no-cache");
//request.AddHeader("Accept", "*/*");
//request.AddHeader("User-Agent", "PostmanRuntime/7.18.0");
//request.AddHeader("Content-Type", "text/plain");
request.AddParameter("application/json", "{\"Item No\":\"3101\"}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
var content = response.Content;
textBox1.Text = content;
}
but it is still output "No JSON object could be decoded" after GET request.
Anyone share your experience will be appreciated.
or there are other ways to do GET/POST on C#.
thanks.!
You can use httpclient and pass parameters as stringcontent and type should be application/json for stringcontent.
This is for post request
Getting StatusCode: UnsupportedMediaType for file upload. I am using RestClient with bearer token
I got the bearer token successfully, but when sending the JSON to the API I'm getting the exception unsupported media type
var client = new RestClient(requestAPIURL);
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Authorization", string.Format("Bearer " +
token.AccessToken));
request.AddParameter("application/json",
JsonConvert.SerializeObject(jsonData), ParameterType.RequestBody);
var response = client.Execute(request);
POST the JSON in the request body:
request.AddBody(JsonConvert.SerializeObject(jsonData));
I am using RestSharp to make a GET api call. The api call is authenticated through HTTP Basic authentication by passing the authorization header.
The server redirects the api call with a status code 307. My client code does handle the redirects but the authorization header is not passed to this redirected api call. This is done for valid reasons as mentioned here. Hence I do get an unauthorized error.
How can I configure the RestClient to restore the authorization header?
var client = new RestClient("https://serverurl.com");
var request = new RestRequest(Method.GET);
request.AddHeader("Authorization", "Basic Z3JvdXAxOlByb2otMzI1");
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Tenant-Id", "4892");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
I added a check that resends the api request of receiving a 401 with the below code.
var client = new RestClient("https://serverurl.com");
var request = new RestRequest(Method.GET);
request.AddHeader("Authorization", "Basic Z3JvdXAxOlByb2otMzI1");
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Tenant-Id", "4892");
IRestResponse response = client.Execute(request);
//Resend the request if we get 401
int numericStatusCode = (int)response.StatusCode;
if(numericStatusCode == 401) {
var redirectedClient = new RestClient(response.ResponseUri.ToString());
IRestResponse newResponse = redirectedClient.Execute(request);
Console.WriteLine(newResponse.ResponseStatus);
}
var client = new RestClient("https://seller.digikala.com/Account/Login");
var request = new RestRequest(Method.POST);
request.AddHeader("postman-token", "0e4d8dba-29da-0b26-1b43-1bf974e9b5de");
request.AddHeader("cache-control", "no-cache");
request.AddHeader("content-type", "application/x-www-form-urlencoded");
IRestResponse response = client.Execute(request);
I can send request successfully and login to site in postman, but I can't do it in VS. This is my code in VS:
var client = new RestClient("https://seller.digikala.com/Account/Login");
var request = new RestRequest(Method.POST);
request.AddParameter("IsPersistent", true, ParameterType.GetOrPost);
request.AddParameter("Password", "myPass", ParameterType.GetOrPost);
request.AddParameter("UserName", "myUsername", ParameterType.GetOrPost);
request.AddParameter("returnUrl", "/Account/Login", ParameterType.GetOrPost);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("content-type", "application/x-www-form-urlencoded");
IRestResponse response = client.Execute(request);
but I get "unauthorized" message (401) in VS
you can use PostMan Auto C# Code generator
I believe your issue is that you're adding things that should be part of the body as parameters (based on the screenshot from PostMan showing these items as part of the body). This is untested but may work for you.
var client = new RestClient("https://seller.digikala.com/Account/Login");
var request = new RestRequest(Method.POST);
request.AddBody(new
{
IsPersistant = true,
Password = "myPass",
UserName = "myUsername",
returnUrl = "/Account/Login"
});
request.AddHeader("cache-control", "no-cache");
request.AddHeader("content-type", "application/x-www-form-urlencoded");
IRestResponse response = client.Execute(request);
You probably need to do a GET of the page first, then when making then POST reflect back all cookies received during the GET (if that RestClient of yours doesn't do that automatically).
Login pages typically add a cookie during GET and expect that cookie during POST to prevent XSRF (this involves including that same token as a form's hidden field, although the XSRF token is apparently not present in your Postman payload). It also wouldn't surprise me that some cookie-based sessionID filter is blocking you even before your request hits the login controller/middleware. In any case, doing the GET first and then reflecting the cookies in POST should work.