1

I am trying to send a POST request from my ASP.NET Core Web API Project but the request is never sent. The method gets executed with no errors but the request never gets sent out from the async method.

My Implementation:

public async void notify(String message)
{    
    String url = "MY_WEBSERVICE_URL";
    var client = new HttpClient();
    client.BaseAddress = new Uri(url);
    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "relativeAddress");
    request.Content = new StringContent("application/x-www-form-urlencoded;charset=UTF-8",
    Encoding.UTF8, "application/json");

    Byte[] byteArray = Encoding.UTF8.GetBytes("{\"text\":\"" + message + "\"}");
    request.Content.Headers.ContentLength = byteArray.Length;

    await client.SendAsync(request).ContinueWith(responseTask =>
    {
       Console.WriteLine("Response: {0}", responseTask.Result);
    });
}

Is this the proper way of making a POST request from a Core Web API project? Thank you in advance

1
  • Why are you using async void? Use async Task. Commented Jul 4, 2017 at 10:24

2 Answers 2

1

First of all, there is a dedicated method PostAsync in the HttpClient class ( or even PostAsJsonAsync extension) which you can use to send POST requests without creating HttpRequstMessage manually.

Now about your code - I believe you want to post following JSON string:

{"text":"someMessage"}

You should set this string as a content of StringContent which you are sending:

var json = "{\"text\":\"" + message + "\"}";
request.Content = new StringContent(json, Encoding.UTF8, "application/json");

Currently you are trying to post mediatype string as a value to your API endpoint. Of course it cannot be deserialized into your model.

Note1: StringContent will automatically add Content-Length header with the appropriate value. You should not do that manually.

Note2: Unless this is an event handler, you should not use async void - use async Task instead.


Same task with PostAsJsonAsync usage will look like:

public async Task Notify(string message)
{
   var string url = "MY_WEBSERVICE_URL";
   var client = new HttpClient();
   client.BaseAddress = new Uri(url);
   var notification = new Notification { Text = message }; // use some model class
   var resonse = await client.PostAsJsonAsync("relativeAddress", notification);
   if (response.IsSuccessStatusCode)
   {
       var content = await response.Content.ReadAsStringAsync();
   }
}

In this case, your model will be automatically serialized into JSON, appropriate content will be created and POST request will be sent.

Sign up to request clarification or add additional context in comments.

2 Comments

Hey thanks for the detailed answer. But I got the error HttpClient does not contain a definition for PostAsJsonAsync. I found that I was missing the library Microsoft.AspNet.WebApi.Client. Problem is, that reference doesn't get added and fails with the error message: One or more packages are incompatible with .NETCoreApp,Version=v1.1 (win-x86). Any solution?
@RickGrimesTheCoder my bad - looks like this extension is not ported to .net core yet. But you can write your own which does the same thing and calls PostAsync as described here
0

Try Adding [IgnoreAntiforgeryToken] on top of the Post Action like this

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.