Romonov
Romonov

Reputation: 8605

C# Read http post result

I have the following code in a MVC controller that is putting a sample guid string into a HttpResponseMessage:

public class CertifyController : Controller
{
    [HttpPost]
    public async Task<HttpResponseMessage> NewCertifyOfferRequestAsync(string requestString)
    {
        string activityId = "30dd879c-ee2f-11db-8314-0800200c9a66";

        HttpResponseMessage httpResponseMessage = new HttpResponseMessage();
        httpResponseMessage.Content = new StringContent(activityId);
        return httpResponseMessage;
    }

}

I am calling this Controller through a console app using the following code:

using (HttpClient client = new HttpClient())
{
    client.BaseAddress = new Uri("http://localhost:84928/");

    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    string requestString = "df5f5587-f1ef-449a-9d20-7f386ea638a8";

    HttpResponseMessage response = await client.PostAsJsonAsync("Certify/NewCertifyOfferRequestAsync", requestString);
    if (response.IsSuccessStatusCode)
    {
        string activityId = await response.Content.ReadAsStringAsync();
        Console.WriteLine("Received activity id: " + activityId);
    }
}

I am expecting to receive activityId "30dd879c-ee2f-11db-8314-0800200c9a66" in the response. But instead activityId is getting "StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.StringContent, Headers:\r\n{\r\n Content-Type: text/plain; charset=utf-8\r\n}" from the ReadAsStringAsync call.

How should I change the assignment of activityId so that it gets the activityId being generated in the Controller?

Upvotes: 2

Views: 1828

Answers (1)

Xiaomin Wu
Xiaomin Wu

Reputation: 3777

if it is webapi, you should be able to change your method signature to return a "string" instead of HttpResponseMessage.

e.g

public string Get(int id)
{
    return "value";
}

for detail sample, you can use visual studio to create a WebApi web app, and look at the "ValuesController.cs"

Upvotes: 3

Related Questions