2

I am trying the run the console application as a window service in dot-net core and able to create ,start ,stop and delete the service.
I am using PostAsync() method in application but the issue is that this method is working perfectly in console application but in window service most of the times PostAsync() never returned any response.

Any help would be highly appreciated. Thanks!

string abc=\"firstparameter\":\"English\",\"secondParameter\":\"Hindi\",\"Marks\":\"Result \"}";
var response = await client.PostAsync("url", new StringContent(ab, Encoding.UTF8, "application/json")).ConfigureAwait(false))

and By this way

var response = client.PostAsync("url", content).Result;
var objResult = response.Content.ReadAsStringAsync().Result;

2 Answers2

0

Here is an example of how you can use it. In this example I have used HttpClientFactory to create a HttpClient.

var userApi = httpClientFactory.CreateClient("UserApi");
var request = new HttpRequestMessage(HttpMethod.Post, "systemuser/login");
request.Content = new StringContent(JsonConvert.SerializeObject(loginRequest), Encoding.UTF8, "application/json");

var response = await userApi.SendAsync(request);

if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
    var body = await response.Content.ReadAsAsync<LoginResponse>();
    return Ok(body);
}
return StatusCode((int)response.StatusCode);

Hope this helps

Ciarán Bruen
  • 5,221
  • 13
  • 59
  • 69
Burim Hajrizaj
  • 383
  • 4
  • 14
  • we can not use the dot net core application exe directly in our service. So I changed the approach Just created the window service application with exe and then used this service exe further in my another service .It solved my problem Thanks!! – Jagjit Saini Mar 31 '21 at 09:30
0

I know this is a late response but just in case this could help someone here is my answer.

StringContent is not a good option when doing Post. You may want to use FormUrlEncodedContent:

var data = new Dictionary<string, string>
{
    { "firstparameter", "firstparametervalue" },
    { "secondparameter", "secondparametervalue" }
};

var content = new FormUrlEncodedContent(data);

var response = await client.PostAsync(apiUri, content);
cgalev
  • 321
  • 2
  • 9