简体   繁体   English

C#阅读http发布结果

[英]C# Read http post result

I have the following code in a MVC controller that is putting a sample guid string into a HttpResponseMessage: 我在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;
    }

}

I am calling this Controller through a console app using the following code: 我使用以下代码通过控制台应用程序调用此Controller:

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. 我期待在回复中收到activityId“30dd879c-ee2f-11db-8314-0800200c9a66”。 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. 但相反,activityId获得“StatusCode:200,ReasonPhrase:'OK',版本:1.1,内容:System.Net.Http.StringContent,标题:\\ r \\ n {\\ r \\ n内容类型:text / plain; charset来自ReadAsStringAsync调用的“utf-8 \\ r \\ n}”。

How should I change the assignment of activityId so that it gets the activityId being generated in the Controller? 我应该如何更改activityId的赋值,以便它在Controller中生成activityId?

if it is webapi, you should be able to change your method signature to return a "string" instead of HttpResponseMessage. 如果是webapi,您应该能够更改方法签名以返回“字符串”而不是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" 对于详细示例,您可以使用visual studio创建WebApi Web应用程序,并查看“ValuesController.cs”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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