user6824563
user6824563

Reputation: 815

Get HttpPost response string in HttpClient

I have an web api that do a POST and return a string:

[HttpPost]
    public string Post([FromBody] Property p)
    {
        // My code where I'll get success and/or Error string message
        if(success)
            return string.Format("OK");
        else
            return string.Format(Error);
    }

I have a .net that calls this HttpPost:

HttpClient client = new HttpClient();
client.BaseAddress = new Uri(URL);

var myContent = JsonConvert.SerializeObject(myData);
var buffer = System.Text.Encoding.UTF8.GetBytes(myContent);
var byteContent = new ByteArrayContent(buffer);
byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");

var result = client.PostAsync("", byteContent).Result;
var contents = result.Content.ReadAsStreamAsync().Result;

I expect to have in the variable contents the value "OK" or Error string. However contents receive an System.IO.MemoryStream

If I run in the Postman, I get the "OK" as return.

Does anyone know why?

Upvotes: 0

Views: 3699

Answers (1)

cuongle
cuongle

Reputation: 75296

You should use ReadAsStringAsync method:

var contents = result.Content.ReadAsStringAsync().Result;

Upvotes: 1

Related Questions