简体   繁体   中英

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?

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

eg

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM