读取http post结果

本文关键字:结果 post http 读取 | 更新日期: 2023-09-27 18:18:34

我在MVC控制器中有以下代码,它将示例guid字符串放入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;
    }
}

我通过控制台应用程序使用以下代码调用这个控制器:

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);
    }
}

我期待在回复中收到活动id"30dd879c-ee2f-11db-8314-0800200c9a66"。但相反,activityId正在获取"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}"从ReadAsStringAsync调用。

我应该如何改变activityId的分配,使它得到在控制器中生成的activityId ?

读取http post结果

如果它是webapi,你应该能够改变你的方法签名返回一个"字符串"而不是HttpResponseMessage。

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

作为详细示例,你可以使用visual studio创建一个WebApi web应用,并查看"ValuesController.cs"