Send parameters & file in Request Body with Origin Request Header C# - c#

I am trying to send parameters & file in Request Body with Origin Request Header C# Console / Asp.Net (Web Form) Web Application.
I have looked around many examples but I didn't get proper solutions.
I've tried with the following code which is almost working. The only issue with couldn't get any solution to send the file in Request Body.
public class requestObj
{
public string langType { get; set; }
}
protected void CreateUser_Click(object sender, EventArgs e)
{
try
{
var requestObj = new requestObj
{
langType = "aaa"
};
var client = new RestSharp.RestClient(url);
client.Timeout = -1;
var request = new RestSharp.RestRequest(RestSharp.Method.POST);
request.AddHeader("Origin", "http://localhost:8080");
request.AddJsonBody(requestObj);
var response = client.Execute(request);
}
catch (Exception ex)
{
throw ex;
}
}
Thanks,

I have made it working following ways,
string url = requestUrl;
string filePath = #"F:\text.txt";
var client = new RestSharp.RestClient(url);
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Origin", "http://localhost:2020");
request.AddParameter("parameter", "parameterValue");
request.AddFile("file", filePath, "text/plain"); //file parameter.
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);

Related

bytes[] not receiving at web api using HttpClient C#

I'm sending bytes[] to .net core web api method(from Windows application to web API) by using HttpClient with below code
HttpClientHandler clientHandler = new HttpClientHandler();
clientHandler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; };
clientHandler.UseDefaultCredentials = true;
// Pass the handler to httpclient(from you are calling api)
HttpClient client2 = new HttpClient(clientHandler);
client2.DefaultRequestHeaders.Clear();
//client2.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/octet-stream"));
client2.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/octet-stream"); // octet-stream");
client2.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "application/octet-stream");
client2.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:19.0) Gecko/20100101 Firefox/19.0");
//client2.DefaultRequestHeaders.Add("Accept", "application/octet-stream");
var content = new ByteArrayContent(fileData);
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
var response = client2.PostAsync("https://mywebsite.com/api/FileHandlingAPI/UploadFiles?filePath=abc", content).Result;
and web api method is
[Route("UploadFiles")]
[HttpPost]
public ActionResult PostDataHello([FromBody]byte[] rawData,string filePath)
{
try
{
System.IO.File.WriteAllBytes(#"C:\WordAutomation\home.zip", rawData);
return StatusCode(200);
}
catch (Exception ex)
{
return StatusCode(500, $"Error. msg: {ex.Message}");
}
}
above code working while development but after hosting in server it is not working as expected. var response receiving 200 Statuscode but bytes[] not receiving at web api method.
any suggestions or changes required above code ?
I think the Content-Type is set to JSON, which is invalid for uploading binary data in the payload.
Try
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
Above code working while development but after hosting in server it is
not working as expected. var response receiving 200 Statuscode but
bytes[] not receiving at web api method. any suggestions or changes
required above code?
Well, not sure how are getting data on local server becuse, you are sending MultipartFormData means your POCO object which is file path and byte array. As you may know we can send json object in FromBody but not the files as json. Thus, I am not sure how it working in local, and getting null data is logical either in server like IIS Or Azure.
My take on this, for sending both POCO object and Files as byte or stream we need to use FromForm and beside that, we need to bind our request object as MultipartFormDataContent to resolve your null data on your PostDataHello API action.
Required Change For Http Client:
Http Client Request Model:
public class HttpClientReqeustModel
{
public string FilePath { get; set; }
public string FileName { get; set; }
public byte[] MyByteData { get; set; }
}
Http Client Request:
public async Task<IActionResult> SendByteDataToAPIControllre()
{
HttpClientHandler clientHandler = new HttpClientHandler();
clientHandler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; };
clientHandler.UseDefaultCredentials = true;
HttpClient client2 = new HttpClient(clientHandler);
client2.DefaultRequestHeaders.Clear();
//Bind Request Model
var requestMode = new HttpClientReqeustModel();
requestMode.MyByteData = System.IO.File.ReadAllBytes(#"D:\YourFile.pdf");
requestMode.FilePath = #"D:\YourFilePath.pdf";
requestMode.FileName = "YourFileNameYourWantToSet.pdf";
//Create Multipart Request
var formContent = new MultipartFormDataContent();
formContent.Add(new StringContent(requestMode.FilePath), "FilePath");
formContent.Add(new StreamContent(new MemoryStream(requestMode.MyByteData)), "MyByteData", requestMode.FileName);
var response = await client2.PostAsync("http://localhost:5094/UploadFiles", formContent);
return Ok();
}
Change For Asp.net Core Web API:
API Model:
public class APIRequestModel
{
public string FilePath { get; set; }
public IFormFile MyByteData { get; set; }
}
Controller:
[Route("UploadFiles")]
[HttpPost]
public async Task<ActionResult> PostDataHello([FromForm] APIRequestModel requestModel)
{
try
{
var path = Path.Combine(_environment.WebRootPath, "WordAutomation/",requestModel.MyByteData.FileName);
using (FileStream stream = new FileStream(path, FileMode.Create))
{
await requestModel.MyByteData.CopyToAsync(stream);
stream.Close();
}
// System.IO.File.WriteAllBytes(#"C:\WordAutomation\home.zip", rawData);
return StatusCode(200);
}
catch (Exception ex)
{
return StatusCode(500, $"Error. msg: {ex.Message}");
}
}
Output:
Update:
For WinForm and WPF App:
private async void button1_Click(object sender, EventArgs e)
{
HttpClientHandler clientHandler = new HttpClientHandler();
clientHandler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; };
clientHandler.UseDefaultCredentials = true;
HttpClient client2 = new HttpClient(clientHandler);
client2.DefaultRequestHeaders.Clear();
//Bind Request Model
var requestMode = new HttpClientReqeustModel();
requestMode.MyByteData = System.IO.File.ReadAllBytes(#"D:\Md Farid Uddin Resume.pdf");
requestMode.FilePath = #"D:\Md Farid Uddin Resume.pdf";
requestMode.FileName = "MyFilename.pdf";
//Create Multipart Request
var formContent = new MultipartFormDataContent();
formContent.Add(new StringContent(requestMode.FilePath), "FilePath");
formContent.Add(new StreamContent(new MemoryStream(requestMode.MyByteData)), "MyByteData", requestMode.FileName);
var response = await client2.PostAsync("http://localhost:5094/UploadFiles", formContent);
}
Output:

C# - Problems on Connect to Synology NAS with Restsharp

I can't manage to stablish a connection to Synology NAS from c# using RestSharp (or any other method)
public void TryConnection()
{
var request = new RestRequest("/webapi/entry.cgi", Method.Post);
request.AddParameter("path", "entry.cgi");
request.AddParameter("api", "SYNO.API.Info");
request.AddParameter("version", "1");
request.AddParameter("method", "query");
var client = new RestClient(new RestClientOptions("http://quickconnect.to/FDesign-GmbH:5000/") { FollowRedirects = true });
var response = client.ExecuteGetAsync(request).Result;
string s = response.ResponseUri.ToString();
}
Result = "Request failed with status code Redirect".
from what i found i believe this is having something to do with redirects but i dont know how to handle it...
if i paste this Url manualy in browser i get feedback :
https://192-168-178-23.fdesign-gmbh.direct.quickconnect.to:5001/webapi/entry.cgi?api=SYNO.API.Info&version=1&method=query
same Url in Code:
public void TryConnection()
{
var request = new RestRequest("/webapi/entry.cgi", Method.Post);
//request.AddParameter("path", "entry.cgi");
request.AddParameter("api", "SYNO.API.Info");
request.AddParameter("version", "1");
request.AddParameter("method", "query");
request.AddParameter("query", "SYNO.API.Auth,SYNO.FileStation");
var client = new RestClient(new RestClientOptions("https://192-168-178-23.fdesign-gmbh.direct.quickconnect.to:5001/") { FollowRedirects = false });
var response = client.ExecuteGetAsync(request).Result;
string s = response.ResponseUri.ToString();
}
with code i get : "Error sending request"
Some help on this would be appreciated.

C# RestClient returning "Login Required" when Login Details are specified

Just started at a new company and we all use Jira, the customers are determined to not use it as they don't like it so I have decided to build a simple Windows Form when they can both Log tickets and get Updates and Comments in a nice simple UI.
Now I have never done any coding before 2 weeks ago so it has been a struggle to get my head around both C# and Rest (Have made scripts for basic IT fixes but never anything as complex as this!)
Back onto point, Set up and got a Rest API set up with a Rest Client but everytime I try pull data from a ticket on Jira I get the error:
{"errorMessages":["You do not have the permission to see the specified issue.","Login Required"],"errors":{}}
Here is the code from the Form:
private void button3_Click_1(object sender, EventArgs e)
{
var client = new RestClient("https://jira.eandl.co.uk/rest/api/2/issue/ITREQ-" + textBox1.Text
);
client.Authenticator = new SimpleAuthenticator("username", "abc", "password", "123");
var request = new RestRequest(Method.GET);
request.AddParameter("token", "saga001", ParameterType.UrlSegment);
// request.AddUrlSegment("token", "saga001");
request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
var queryResult = client.Execute(request);
Console.WriteLine(queryResult.Content);
}
And here is the code from the Rest Client itself:
public Restclient()
{
endPoint = string.Empty;
httpMethod = httpVerb.GET;
}
private string logonAttempt;
public string makeRequest()
{
string strResponseValue = string.Empty;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(endPoint);
request.Method = httpMethod.ToString();
String authHeader = System.Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(userName + ":" + userPassword));
request.Headers.Add("Authorization", authType.ToString() + " " + authHeader);
HttpWebResponse response = null;
try
{
response = (HttpWebResponse)request.GetResponse();
//Process the Response Stream... (Could be JSON, XML ot HTML etc...)
using (Stream responseStream = response.GetResponseStream())
{
if (responseStream != null)
{
using (StreamReader reader = new StreamReader(responseStream))
{
strResponseValue = reader.ReadToEnd();
}//End of Stream Reader
}
}//end of Response Stream
}
catch (Exception ex)
{
strResponseValue = "(\"errorMessages\":[\"" + ex.Message.ToString() + "\"],\"errors\":{}}";
}
finally
{
if(response != null)
{
((IDisposable)response).Dispose();
}
}
return strResponseValue;
}
}
}
Now obviously I am expecting that I have missed something absolutely bigginer as like I said, I've never taken on a project like this before and had 0 experience.
Just looking for someone to bluntly tell me what I'm doing wrong
Changed to this as per answer:
private void button3_Click_1(object sender, EventArgs e)
{
var client = new
RestClient("https://jira.eandl.co.uk/rest/api/2/issue/ITREQ-" + textBox1.Text
);
client.Authenticator = new HttpBasicAuthenticator("username", "password");
var request = new RestRequest(Method.GET);
string authHeader = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes("cdale!" + ":" + "Chantelle95!"));
request.AddHeader("Authorization", "Basic " + authHeader);
request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
var queryResult = client.Execute(request);
Console.WriteLine(queryResult.Content);
}
By default with the Jira REST API, you can use Basic Authentication or OAuth2. I think that more easy way for you will be to use the Basic one.
I'm not sure why you have a class where you define your custom RestClient since the first block of code uses the RestSharp one from http://restsharp.org.
In this case, you will need to modify your authenticator:
client.Authenticator = new HttpBasicAuthenticator(userName, password);
And I think that you should remove the line where you specify a token. I don't think that it's required.
Finally, the class Restclient doesn't seem to be used, then remove it.
You could also uses what you have created in your custom RestClient and manually specify a Basic header:
string authHeader = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(userName + ":" + userPassword));
request.AddHeader("Authorization", "Basic " + authHeader);
However, it's essentially the behavior of the HttpBasicAuthenticator class.
If you don't want to encode your credentials in every request here is how to do it using cookies.
When requesting the cookie you don't need to add any authorization on the headers. This method will accept a JSON string with the user name and password and the URL. It will return the cookie values.
public async Task<JiraCookie> GetCookieAsync(string myJsonUserNamePassword, string JiraCookieEndpointUrl)
{
using (var client = new HttpClient())
{
var response = await client.PostAsync(
JiraCookieEndpointUrl,
new StringContent(myJsonUserNamePassword, Encoding.UTF8, "application/json"));
var json = response.Content.ReadAsStringAsync().Result;
var jiraCookie= JsonConvert.DeserializeObject<JiraCookie>(json);
return jArr;
}
}
public class JiraCookie
{
public Session session { get; set; }
}
public class Session
{
public string name { get; set; }
public string value { get; set; }
}
When I call it using url: http://[baseJiraUrl]/rest/auth/1/session it returns the following JSON response:
{
"session" : -{
"name" : JSESSIONID,
"value" : cookieValue
}
Keep in mind the URL above is valid in the version of JIRA I'm using and may vary depending on which version you're using. Read the JIRA API documentation for the correct URL for the version you are using. I'm using the following:
https://docs.atlassian.com/software/jira/docs/api/REST/7.6.1/#auth/1/session
Remember you'll have to store your cookie and use it on every subsequent request.
Check out this answer on how add cookies to your HttpClient request: How do I set a cookie on HttpClient's HttpRequestMessage.
Once you're done with the cookie (logging out) simply send a delete http request with the same URL as the post.
Reference: https://stackoverflow.com/a/49109192/7763903

mailgun email validation response

I am a newbie to Mailgun and REST and need some help.
If I use the Mailgun provided code:
RestClient client = new RestClient();
client.BaseUrl = "https://api.mailgun.net/v2";
client.Authenticator = new HttpBasicAuthenticator("api", "xxxx");
RestRequest request = new RestRequest();
request.Resource = "/address/validate";
request.AddParameter("address", "me#mydomain.com");
return client.Execute(request);
How do I retrieve and process the response that the address is valid or not?
This code works for me. I didn't use RESTClient and wrote my own code(which works perfectly fine)
[System.Web.Services.WebMethod]
public static object GetEmailInfo(string UserName)
{
var http = (HttpWebRequest)WebRequest.Create("https://api.mailgun.net/v2/address/validate?address=" + UserName);
http.Credentials = new NetworkCredential("api","public key");
http.Timeout = 5000;
try
{
var response = http.GetResponse();
var stream = response.GetResponseStream();
var sr = new StreamReader(stream);
var content = sr.ReadToEnd();
JSON.JsonObject js = new JSON.JsonObject(content);
return Convert.ToBoolean(js["is_valid"]);
}
catch (Exception ex)
{
}
}
First of You should never post private information such as your public key of such API
Just by using the amazing Postman Chrome app you can see the result of such request:
click here to see the image below in full resolution
and I'm sure, if you instead of return client.Execute(request); you do
var result = client.Execute(request);
return result;
and adding a breakpoint in the return you can inspect what is the object that is passed from the call... without testing, I'm sure you can convert result.Content (as it's where RestSharp appends the response content) into an object and use that object (or use the dynamic type).
now, testing your code in VS:
click here to see the image below in full resolution
you can then use the dynamic object like:
click here to see the image below in full resolution
public void GetResponse()
{
var client = new RestClient();
client.BaseUrl = "https://api.mailgun.net/v2";
client.Authenticator = new HttpBasicAuthenticator("api", "pubkey-e82c8201c292691ad889ace3434df6cb");
var request = new RestRequest();
request.Resource = "/address/validate";
request.AddParameter("address", "me#mydomain.com");
var response = client.Execute(request);
dynamic content = Json.Decode(response.Content);
bool isValid = content.is_valid;
string domain = content.parts.domain;
}
and treat the content of the response just like the json passed:
{
"address": "me#mydomain.com",
"did_you_mean": null,
"is_valid": true,
"parts": {
"display_name": null,
"domain": "mydomain.com",
"local_part": "me"
}
}

Paypal REST api call works from cURL but not from C# code

I'm trying to call Paypal api from my code. I set up the sandbox account and it works when I use curl but my code isn't working the same way, returning 401 Unauthorized instead.
Here's the curl command as documented by Paypal
curl https://api.sandbox.paypal.com/v1/oauth2/token -H "Accept: application/json" -H "Accept-Language: en_US" -u "A****:E****" -d "grant_type=client_credentials"
UPDATE: Apparently the .Credentials doesn't do the trick, instead setting Authorization header manually works (see code)
Here's the code (trimmed to its essence):
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("https://api.sandbox.paypal.com/v1/oauth2/token");
request.Method = "POST";
request.Accept = "application/json";
request.Headers.Add("Accept-Language:en_US")
// this doesn't work:
**request.Credentials = new NetworkCredential("A****", "E****");**
// DO THIS INSTEAD
**string authInfo = Convert.ToBase64String(System.Text.Encoding.Default.GetBytes("A****:E****"));**
**request.Headers["Authorization"] = "Basic " + authInfo;**
using (StreamWriter swt = new StreamWriter(request.GetRequestStream()))
{
swt.Write("grant_type=client_credentials");
}
request.BeginGetResponse((r) =>
{
try
{
HttpWebResponse response = request.EndGetResponse(r) as HttpWebResponse; // Exception here
....
} catch (Exception x) { .... } // log the exception - 401 Unauthorized
}, null);
This is the request from code captured by Fiddler (raw), there are no authorization parameters for some reason:
POST https://api.sandbox.paypal.com/v1/oauth2/token HTTP/1.1
Accept: application/json
Accept-Language: en_US
Host: api.sandbox.paypal.com
Content-Length: 29
Expect: 100-continue
Connection: Keep-Alive
grant_type=client_credentials
Hoping the following code help to anyone who is still looking for a good piece of cake to get connected to PayPal.
As many people, I've been investing a lot of time trying to get my PayPal token access without success, until I found the following:
public class PayPalClient
{
public async Task RequestPayPalToken()
{
// Discussion about SSL secure channel
// http://stackoverflow.com/questions/32994464/could-not-create-ssl-tls-secure-channel-despite-setting-servercertificatevalida
ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
try
{
// ClientId of your Paypal app API
string APIClientId = "**_[your_API_Client_Id]_**";
// secret key of you Paypal app API
string APISecret = "**_[your_API_secret]_**";
using (var client = new System.Net.Http.HttpClient())
{
var byteArray = Encoding.UTF8.GetBytes(APIClientId + ":" + APISecret);
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
var url = new Uri("https://api.sandbox.paypal.com/v1/oauth2/token", UriKind.Absolute);
client.DefaultRequestHeaders.IfModifiedSince = DateTime.UtcNow;
var requestParams = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("grant_type", "client_credentials")
};
var content = new FormUrlEncodedContent(requestParams);
var webresponse = await client.PostAsync(url, content);
var jsonString = await webresponse.Content.ReadAsStringAsync();
// response will deserialized using Jsonconver
var payPalTokenModel = JsonConvert.DeserializeObject<PayPalTokenModel>(jsonString);
}
}
catch (System.Exception ex)
{
//TODO: Log connection error
}
}
}
public class PayPalTokenModel
{
public string scope { get; set; }
public string nonce { get; set; }
public string access_token { get; set; }
public string token_type { get; set; }
public string app_id { get; set; }
public int expires_in { get; set; }
}
This code works pretty well for me, hoping for you too. The credits belong to Patel Harshal who posted his solution here.
This Works using HttpClient...
'RequestT' is a generic for the PayPal request arguments, however it is not used. The 'ResponseT' is used and it is the response from PayPal according to their documentation.
'PayPalConfig' class reads the clientid and secret from the web.config file using ConfigurationManager.
The thing to remember is to set the Authorization header to "Basic" NOT "Bearer" and if and to properly construct the 'StringContent' object with right media type (x-www-form-urlencoded).
//gets PayPal accessToken
public async Task<ResponseT> InvokePostAsync<RequestT, ResponseT>(RequestT request, string actionUrl)
{
ResponseT result;
// 'HTTP Basic Auth Post' <http://stackoverflow.com/questions/21066622/how-to-send-a-http-basic-auth-post>
string clientId = PayPalConfig.clientId;
string secret = PayPalConfig.clientSecret;
string oAuthCredentials = Convert.ToBase64String(Encoding.Default.GetBytes(clientId + ":" + secret));
//base uri to PayPAl 'live' or 'stage' based on 'productionMode'
string uriString = PayPalConfig.endpoint(PayPalConfig.productionMode) + actionUrl;
HttpClient client = new HttpClient();
//construct request message
var h_request = new HttpRequestMessage(HttpMethod.Post, uriString);
h_request.Headers.Authorization = new AuthenticationHeaderValue("Basic", oAuthCredentials);
h_request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
h_request.Headers.AcceptLanguage.Add(new StringWithQualityHeaderValue("en_US"));
h_request.Content = new StringContent("grant_type=client_credentials", UTF8Encoding.UTF8, "application/x-www-form-urlencoded");
try
{
HttpResponseMessage response = await client.SendAsync(h_request);
//if call failed ErrorResponse created...simple class with response properties
if (!response.IsSuccessStatusCode)
{
var error = await response.Content.ReadAsStringAsync();
ErrorResponse errResp = JsonConvert.DeserializeObject<ErrorResponse>(error);
throw new PayPalException { error_name = errResp.name, details = errResp.details, message = errResp.message };
}
var success = await response.Content.ReadAsStringAsync();
result = JsonConvert.DeserializeObject<ResponseT>(success);
}
catch (Exception)
{
throw new HttpRequestException("Request to PayPal Service failed.");
}
return result;
}
IMPORTANT: use Task.WhenAll() to ensure you have a result.
// gets access token with HttpClient call..and ensures there is a Result before continuing
// so you don't try to pass an empty or failed token.
public async Task<TokenResponse> AuthorizeAsync(TokenRequest req)
{
TokenResponse response;
try
{
var task = new PayPalHttpClient().InvokePostAsync<TokenRequest, TokenResponse>(req, req.actionUrl);
await Task.WhenAll(task);
response = task.Result;
}
catch (PayPalException ex)
{
response = new TokenResponse { access_token = "error", Error = ex };
}
return response;
}
Paypal has deprecated TLS 1.1, and only accepts 1.2 now. Unfortunately .NET (prior to version 4.7) uses 1.1 by default, unless you configure it otherwise.
You can turn on TLS 1.2 with this line. I recomend placing it Application_Start or global.asax.
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
I too suffered from a lack of example code and various issues with response errors and codes.
I am a big fan of RestClient as it helps a lot with integrations and the growing number of RESTful API calls.
I hope this small snippet of code using RestSharp helps someone: -
if (ServicePointManager.SecurityProtocol != SecurityProtocolType.Tls12) ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; // forced to modern day SSL protocols
var client = new RestClient(payPalUrl) { Encoding = Encoding.UTF8 };
var authRequest = new RestRequest("oauth2/token", Method.POST) {RequestFormat = DataFormat.Json};
client.Authenticator = new HttpBasicAuthenticator(clientId, secret);
authRequest.AddParameter("grant_type","client_credentials");
var authResponse = client.Execute(authRequest);
// You can now deserialise the response to get the token as per the answer from #ryuzaki
var payPalTokenModel = JsonConvert.DeserializeObject<PayPalTokenModel>(authResponse.Content);

Categories