When sending a basic GET the response.Content is always NULL on return. The weird thing is that it will log the content on the standard execute, but not on the async. I'm at my wit's end. Any help would be appreciated.
I tried using the standard client.Execute and client.ExecuteAsync and both seem to have the same result, except for the logging part.
The regular method (with identifying info X'd out):
RestClient myClient = new RestClient(uri);
var request = new RestRequest(Method.GET);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("Connection", "keep-alive");
request.AddHeader("accept-encoding", "gzip, deflate");
request.AddHeader("Host", "XXXXX");
request.AddHeader("Cache-Control", "no-cache");
request.AddHeader("Accept", "*/*");
request.AddHeader("Authorization", "XXX");
Serilog.Log.Information($"Request is {request}");
IRestResponse response = myClient.Execute(request);
var htmlString = response.Content;
Serilog.Log.Information($"Request is {response.Content}");
return htmlString;
The executeAsync method:
RestClient myClient = new RestClient(uri);
var request = new RestRequest(Method.GET);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("Connection", "keep-alive");
request.AddHeader("accept-encoding", "gzip, deflate");
request.AddHeader("Host", "XXXXX");
request.AddHeader("Cache-Control", "no-cache");
request.AddHeader("Accept", "*/*");
request.AddHeader("Authorization", "XXXXXXXXXX");
Serilog.Log.Information($"Request is {request}");
var htmlString = "";
myClient.ExecuteAsync(request, response =>
{
htmlString = response.Content;
Serilog.Log.Information($"Response is {response.Content}");
});
return htmlString;
Obviously I want it to both log AND return the actual content. Ok, gurus, what am I doing wrong?
You have to be kidding me. It was working all the time (at least the regular execute), but there was so much whitespace at the beginning of the string that VS 2017 didn't display it as a local. I had to really drill down to see it.
Related
I am using C#, RestSharp to get the bearer token for a sap exposed RestAPI. Here is my code snippet
var client = new RestClient("https://url/oauth2/token");
var request = new RestRequest(Method.POST);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddHeader("Authorization", "Basic clientusername:clientpassword");
request.AddParameter("application/x-www-form-urlencoded", "grant_type=password&username=user&password=pwd", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
But no luck - always get below error
{"fault":{"faultstring":"UrlDecoding of the form parameters from the request message failed. The form parameters needs to be url encoded","detail":{"errorcode":"steps.oauth.v2.InvalidRequest"}}}
I used the psotman with same credentials and it worked fine!!
Any idea?
You might need to use the Authenticator property. Try this
var client = new RestClient($"{_apiBaseUrl}/token")
{
Authenticator = new HttpBasicAuthenticator(_clientId, _clientSecret)
};
var request = new RestRequest(Method.POST);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddParameter("application/x-www-form-urlencoded", $"grant_type=password&username={username}&password={password}&scope=trust", ParameterType.RequestBody);
var response = client.Execute(request);
Below code I need to call in c#, how do we can achieve this, please help me.
import requests #requires "requests" package
import json
response = requests.post('https://scm.commerceinterface.com/api/v3/mark_exported', data={'supplier_id':'111111111', 'token':'sample-token',
'ci_lineitem_ids':json.dumps([54553919,4553920])}).json()
if response['success'] == True:
#Successfully marked as exported (only items which are not already marked exported)
pass
else:
pass
//I got sollution
C# post request
var client = new RestClient(exportUrl);
var request = new RestRequest(Method.POST);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("content-type", "application/json");
request.AddParameter("supplier_id", apiSupplierID);
request.AddParameter("token", apiToken);
request.AddParameter("ci_lineitem_ids", exportOrders);
IRestResponse response = client.Execute(request);
I need to make the following call in REST. Can anyone provide a C# sample on how to do this ?
From:
https://learn.microsoft.com/en-us/azure/active-directory/active-directory-protocols-oauth-code
POST /{tenant}/oauth2/token HTTP/1.1
Host: https://login.microsoftonline.com
Content-Type: application/x-www-form-urlencoded
grant_type=authorization_code
&client_id=2d4d11a2-f814-46a7-890a-274a72a7309e
&code=AwABAAAAvPM1KaPlrEqdFSBzjqfTGBCmLdgfSTLEMPGYuNHSUYBrqqf_ZT_p5uEAEJJ_nZ3UmphWygRNy2C3jJ239gV_DBnZ2syeg95Ki-374WHUP-i3yIhv5i-7KU2CEoPXwURQp6IVYMw-DjAOzn7C3JCu5wpngXmbZKtJdWmiBzHpcO2aICJPu1KvJrDLDP20chJBXzVYJtkfjviLNNW7l7Y3ydcHDsBRKZc3GuMQanmcghXPyoDg41g8XbwPudVh7uCmUponBQpIhbuffFP_tbV8SNzsPoFz9CLpBCZagJVXeqWoYMPe2dSsPiLO9Alf_YIe5zpi-zY4C3aLw5g9at35eZTfNd0gBRpR5ojkMIcZZ6IgAA
&redirect_uri=https%3A%2F%2Flocalhost%2Fmyapp%2F
&resource=https%3A%2F%2Fservice.contoso.com%2F
&client_secret=p#ssw0rd
RestSharp really did make creating these rest calls easier (thanks Soren).
string token = await GetAccessToken();
var client = new RestSharp.RestClient("https://login.microsoftonline.com/common/oauth2/v2.0");
var request = new RestRequest("token");
request.AddParameter("grant_type","authorization_code");
request.AddParameter("client_id", "edd7c078-...f5d4979c7f4e");
request.AddParameter("code", "Ma49210e1-5332-a5dc-4005-70411bf85fbe");
request.AddParameter("redirect_uri", "https://localhost:44333");
request.AddParameter("client_secret", "qZqxfjca6xg0scsNP67KATy");
request.Method = Method.POST;
request.AddHeader("Authorization", "Bearer " + token);
var response = client.Execute(request);
I am working to consume Drupal Rest Api using c#. I am using drupal 7.5 and utilising it's rest services/api following various resources.
I have been successful with google's postman to post the content but when I try to replicate it with c# code I am prompted with forbidden error saying: Access denied for user anonymous.
I am utilising rest-sharp to consume this API. I have researched quite a lot and haven't found solution yet,as well as haven't noticed anyone doing this work in c#.
Following is the code snippet that I have written based on postman
var client = new RestClient("drupasitename/rest/node");
var request = new RestRequest(Method.POST);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("authorization", authorisation);
request.AddHeader("x-csrf-token", token);
request.AddHeader("cookie", cookie);
request.AddHeader("content-type", "application/json");
request.AddHeader("Accept", "application/json");
request.AddParameter("application/json", "{\r\n \"type\":\"page\",\r\n \"title\":\"Page submitted via JSON REST\",\r\n \"body\":{\r\n \"und\":[\r\n {\r\n \"value\":\"This is the body of the page.\"\r\n }\r\n ]\r\n }\r\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
cookie and token are obtained after successful login attempt using c# code.
It would be great if anyone could provide a guidance to solve this issues.
Regards
All you need is adding UserAgent into http request header
I got the user information include the cookie & token .
private login_user LoginAsync(string username,string password)
{
try
{
RestClient client = new RestClient(base_url);
var request = new RestRequest("login", Method.GET);
request.AddHeader("Content-Type", "Application/JSON");
client.Authenticator = new HttpBasicAuthenticator(username, password);
var restResponse = client.Execute(request);
var content = restResponse.Content;
string context_modifytoken = content.ToString().Replace("X-CSRF-Token", "X_CSRF_Token");
var current_login_user = JsonConvert.DeserializeObject<login_user>(context_modifytoken);
current_login_user.data.session_name = restResponse.Cookies[0].Name;
current_login_user.data.session_id = restResponse.Cookies[0].Value;
return current_login_user;
}
catch (HttpRequestException ex) { throw ex; }
}
And the Post section:
RestClient client = new RestClient(base_url);
var request = new RestRequest("v1.0/barcodes", Method.POST);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("X-CSRF-Token", current_user.data.X_CSRF_Token);
request.AddHeader("content-type", "application/json");
request.AddHeader("Accept", "application/json");
request.AddHeader("cookie", current_user.data.session_name+"="+ current_user.data.session_id);
request.AddHeader("User-Agent", ver);
var queryresult = client.Execute(request);
has error :queryresult = "StatusCode: Forbidden, Content-Type: application/problem+json; charset=utf-8, Content-Length: -1)"
and Drupal log :
restful 2016-09-21 16:32 You do not have access to create a new Sample Barcode... Anonymous (not verified)
I used following to login to drupal
var client = new RestClient("drupalsitename/user/login");
var request = new RestRequest(Method.POST);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("content-type", "application/json");
request.AddHeader("user-agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:48.0) Gecko/20100101 Firefox/48.0");
request.AddParameter("application/json", "{\"name\":\"username\",\n\"pass\":\"password\"}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
This will provide you with necessary session and token info and then basically you can use those information to make the post, similar to that I have written in the question
I have wcf sharepoint. And I use RestSharp client:
var json = new JsonSerializer().Serialize((objectToUpdate));
var request = new RestRequest(apiEndPoint, Method.POST);
request.Timeout = 180000;
request.AddHeader("X-FORMS_BASED_AUTH_ACCEPTED", "f");
request.AddHeader("Cache-Control", "no-cache");
request.AddHeader("login", _login);
request.AddHeader("password", _password);
request.AddHeader("Content-Length", objectToUpdate.ToString().Length.ToString());
request.AddParameter("text/json", json, ParameterType.RequestBody);
var response = client.Execute<T>(request);
And I get error Request Entity Too Large.
I try add parameter maxRequestLength="{REQUEST_LENGTH}" in config wcf but not
ineffectually.