Since I've had great help by community before, I have the following problem.
I created a HttpClient to get some information from a Rest API Client. When I send a PostAsync Or SendAsync or whatever, the METHOD (http) is somehow always a GET method?
For information purpose ill send the whole Class.
FYI: both methods do the same thing. Its just for testing!
The following stackoverflow post exactly explains my problem but not the solution: https://stackoverflow.com/questions/62579558/httpclient-postasync-performs-get-request-anyway
Also postman is working fine!
namespace Nop.Plugin.Shipping.DHL.Services
{
public class DHLStandardHttpClient
{
#region Fields
private readonly HttpClient _httpClient;
private readonly DHLSettings _dhlSettings;
#endregion
#region Ctor
public DHLStandardHttpClient(
HttpClient httpClient,
DHLSettings dhlSettings)
{
httpClient.BaseAddress = new Uri(dhlSettings.ApiUrl);
httpClient.Timeout = TimeSpan.FromSeconds(20);
httpClient.DefaultRequestHeaders.Add(HeaderNames.UserAgent, $"nopCommerce-{NopVersion.CurrentVersion}");
_httpClient = httpClient;
_dhlSettings = dhlSettings;
}
#endregion
#region Methods
public async Task<string> PostModelAuthenticationAsync()
{
try
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(_dhlSettings.ApiUrl);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
DHLApiRequestModel model = new DHLApiRequestModel()
{
UserId = _dhlSettings.UserID,
Key = _dhlSettings.Key,
AccountNumber = new List<string>()
{
_dhlSettings.AccountNumber
}
};
var requestMessage = JsonConvert.SerializeObject(model);
var content = new StringContent(requestMessage, Encoding.UTF8, "application/json");
var response = await client.PostAsync("/authenticate/api-key", content);
var responseContentString = await response.Content.ReadAsStringAsync();
return responseContentString;
}
catch (Exception ex)
{
return ex.Message;
}
}
public async Task<string> PostHttpReqMessageAsync()
{
var values = new Dictionary<string, string>();
values.Add("userId", _dhlSettings.UserID);
values.Add("key", _dhlSettings.Key);
values.Add("AccountNumber", _dhlSettings.AccountNumber);
var content = new FormUrlEncodedContent(values);
var url = _dhlSettings.ApiUrl + "/authenticate/api-key";
using (var client = new HttpClient())
{
try
{
var httpReqMessage = new HttpRequestMessage(HttpMethod.Post, url)
{
Content = content
};
var httpResponseMessage = await client.SendAsync(httpReqMessage);
if (httpResponseMessage.StatusCode == System.Net.HttpStatusCode.OK)
{
var resp = await httpResponseMessage.Content.ReadAsStringAsync();
return resp;
}
}
catch (Exception ex)
{
return ex.Message;
}
}
return null;
}
#endregion
}
}
Result: Method: GET, RequestUri: 'https://api-gw.dhlparcel.nl/authenticate/api-key', Version: 1.1, Content: <null>, Headers: