Debug HttpClient request - http

How can i see exactly what the request sent by the HttpClient will contain?
var httpClient = new HttpClient();
var postData = JsonConvert.SerializeObject(
new
{
merchantId = _merchantId,
amount = _amount,
paymentRef = _paymentRef,
customer_ref = _customer_ref,
successUrl = _successUrl,
error_url = _error_url,
currency = _currency,
hash = "fsdfsdfsdf"
});
HttpResponseMessage response = await httpClient.PostAsync(url, new StringContent(postData));

Related

How can I pass header and parameter with HttpClient in .NET Core

This is my code using the RestSharp library:
var client = new RestClient("https://example.com/api");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer token...");
request.AddHeader("Content-Type", "text/plain");
request.AddParameter("text/plain", "{{\"post\":{{\"contact\":{{\"isActive\":true,\"phone\":\"99999999\"}}", ParameterType.RequestBody);
IRestResponse response = await client.ExecuteAsync(request);
// Console.WriteLine(response.Content);
// var res = response.Content;
How can I convert it to HttpClient using best practices?
You can use this:
var client = new HttpClient()
{
BaseAddress = new Uri("https://example.com"),
Timeout = TimeSpan.FromMinutes(5) //default is 90 seconds
};
client.DefaultRequestHeaders.Add("Authorization", "Bearer token...");
var body = new StringContent("{{\"post\":{{\"contact\":{{\"isActive\":true,\"phone\":\"99999999\"}}",Encoding.UTF8, "text/plain");
var response = await client.PostAsync("api", body);
var responseString = await response.Content.ReadAsStringAsync();
And for using the HttpClient in the right way I highly recommend to see this link.

how to call an asyn webmethod in asp.net website

I am using an async web method to fetch data from an external URL. I am using this web service as reference in another asp.net web application.But the web methods which are async are not returning any value.How to call an async web method in asp.net web application.
My web method code
[WebMethod]
public async Task<string> GetTrID()
{
var uri = new System.Uri("//URL");
var json = JsonConvert.SerializeObject(new { //values});
var response = await fnabc(uri, HttpMethod.Post, json, 120);
var content = await response.Content.ReadAsStringAsync();
System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
var objValidate = js.Deserialize<class>(content);
return objValidate.RespObj;
}
private async Task<HttpResponseMessage> fnabc(Uri uri, HttpMethod method, string json, int timeOut)
{
HttpClient client = new HttpClient();
client.MaxResponseContentBufferSize = int.MaxValue;
client.Timeout = TimeSpan.FromSeconds(timeOut);
var request = new HttpRequestMessage(method, uri);
request.Headers.Accept.Clear();
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
request.Content = new StringContent(json, Encoding.UTF8, "application/json");
var response = new HttpResponseMessage();
HttpContent objCnt = new StringContent(json,Encoding.UTF8, "application/json");
response = client.PostAsync(uri.ToString(), objCnt).Result;
return response;
}

consuming API httpClient

I am getting error "Bad Request" trying to consum an API. I had tryed some diferents ways, but without success. Could some one help?
API Parameters must be:
FormData Parameters
scope = "oob"
grant_type = "client_credentials"
Header Parameters
Content-type = "application/x-www-form-urlencoded"
Authorization = "Basic 2xpZW50LTAxOnNlY3JldC1rZXktMDI=" (Base64 example)
[POST]
curl -X POST \
https://api-sandbox.getnet.com.br/auth/oauth/v2/token \
-H 'authorization: Basic 2xpZW50LTAxOnNlY3JldC1rZXktMDI=' \
-H 'content-type: application/x-www-form-urlencoded' \
-d 'scope=oob&grant_type=client_credentials'
string content_type = "application/x-www-form-urlencoded";
string scope = "oob";
string grant_type = "client_credentials";
string authorization = "Basic 2xpZW50LTAxOnNlY3JldC1rZXktMDI="
using (var httpClient = new HttpClient())
{
var requestMessage = new HttpRequestMessage()
{
Method = new HttpMethod("POST"),
RequestUri = new Uri("https://api-sandbox.getnet.com.br/auth/oauth/v2/token"),
Content = new StringContent(
#"{""scope"":""oob"",""grant_type"":client_credentials}", Encoding.UTF8, content_type)};
requestMessage.Content.Headers.ContentType =
new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded");
requestMessage.Headers.Add("Authorization", authorization);
var response = await httpClient.SendAsync(requestMessage);
var responseStatusCode = response.StatusCode;
var responseBody = await response.Content.ReadAsStringAsync();
}
You can try following code snippets
string content_type = "application/x-www-form-urlencoded";
string scope = "oob";
string grant_type = "client_credentials";
string authorization = "Basic 2xpZW50LTAxOnNlY3JldC1rZXktMDI=";
using (var httpClient = new HttpClient())
{
var parameters = new List<KeyValuePair<string, string>>() {
new KeyValuePair<string, string>("scope", "oob"),
new KeyValuePair<string, string>("grant_type", "client_credentials")
};
var requestMessage = new HttpRequestMessage()
{
Method = new HttpMethod("POST"),
RequestUri = new Uri("https://api-sandbox.getnet.com.br/auth/oauth/v2/token"),
Content = new FormUrlEncodedContent(parameters)
};
requestMessage.Content.Headers.ContentType =
new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded");
requestMessage.Headers.Add("Authorization", authorization);
var response = await httpClient.SendAsync(requestMessage);
var responseStatusCode = response.StatusCode;
var responseBody = await response.Content.ReadAsStringAsync();
}

CSOD Unauthorized Exception:Check your credentials

Trying to access Cornerstone list of employees, but getting this error message.
CSOD Unauthorized Exception:Check your credentials
var client = new RestClient("https://xxx.csod.com/services/api/x/users/v1/employees");
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=client_credentials&client_id=xxx&client_secret=xxx", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
My account has permissions to edit and view Employee API. What else could be the problem.
I had the wrong access point:
var client = new RestClient("https://xxx.csod.com/services/api/oauth2/token");
using Newtonsoft.Json.Linq;
using RestSharp;
using System;
namespace TestAPI
{
class Program
{
static void Main(string[] args)
{
String id = "xxx";
String secret = "xxx";
var client = new RestClient("https://xxx.csod.com/services/api/oauth2/token");
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=client_credentials&scope=all&client_id=" + id + "&client_secret=" + secret, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
dynamic resp = JObject.Parse(response.Content);
String token = resp.access_token;
client = new RestClient("https://xxx.csod.com/services/api/x/users/v1/employees");
request = new RestRequest(Method.GET);
request.AddHeader("authorization", "Bearer " + token);
request.AddHeader("cache-control", "no-cache");
response = client.Execute(request);
}
}
}

How to add two authorization headers in HttpClient

I need to add two header of Authorization in HttpClient as below:
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", "XYZNQVJJTkFQUDpX...=");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", jwToken);
But it seems the last one will override the first one.
I need the Basic and Bearer token. Bearer token for me to pass through the Proxy server which host the SAP WebService, the Basic token for the SAP server. In this case, what I should do?
Update:
How to compose 2 HttpRequestMessage?
string webServiceUrl = "https://adfs.xxx.xxx/";
string strURL = "https://xxx.xxx.xxx/";
HttpResponseMessage responseMessage;
HttpClient client = new HttpClient();
//--1st HttpRequestMessage
var tokenRequest = new HttpRequestMessage(HttpMethod.Post, strURL);
tokenRequest.Headers.Authorization = new AuthenticationHeaderValue("Basic", "XYZNQVJJTkFQUDpX...=");
HttpContent httpContent = new FormUrlEncodedContent(
new[]
{
new KeyValuePair<string, string>("grant_type", "xxx"),
new KeyValuePair<string, string>("client_id", "xxx"),
new KeyValuePair<string, string>("scope", "xxx"),
new KeyValuePair<string, string>("assertion", Base64Assertion)
});
tokenRequest.Content = httpContent;
var tokenResponseMessage = await client.SendAsync(tokenRequest);
var token = await tokenResponseMessage.Content.ReadAsStringAsync();
//-- 2nd HttpRequestMessage
var serviceRequest = new HttpRequestMessage(HttpMethod.Get, webServiceUrl);
serviceRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
var serviceResponseMessage = await client.SendAsync(serviceRequest);
In this case, what I should do?
You will need two separate clients, each with their own default authorization header,
client1.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", "XYZNQVJJTkFQUDpX...=");
client2.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", jwToken);
or one client with no default and the authorization set per request.
For example
var tokenRequest = new HttpRequestMessage(HttpMethod.Post, authServerUrl);
tokenRequest.Headers.Authorization = new AuthenticationHeaderValue("Basic", "XYZNQVJJTkFQUDpX...=");
var httpContent = new FormUrlEncodedContent(
new[]
{
new KeyValuePair<string, string>("grant_type", "xxx"),
new KeyValuePair<string, string>("client_id", "xxx"),
new KeyValuePair<string, string>("scope", "xxx"),
new KeyValuePair<string, string>("assertion",Base64Assertion)
});
tokenRequest.Content = httpContent;
var tokenResponseMessage = await client.SendAsync(tokenRequest);
var token = await responseMessage.Content.ReadAsStringAsync();
var serviceRequest = new HttpRequestMessage(HttpMethod.Get, webServiceUrl);
serviceRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
var serviceResponseMessage = await client.SendAsync(serviceRequest);
//...
It has to do more with HTTP.Its not possible to send through multiple Authentication headers

Resources