【问题标题】:Content type in HTTP callHTTP 调用中的内容类型
【发布时间】:2016-07-27 01:06:58
【问题描述】:

我的 HTTP Put 调用响应由以下代码打印。

HttpResponseMessage response = await client.PutAsync("https://restapi.surveygizmo.com/v4/survey/2692209/surveypage/3/surveyquestion?", inputMessage.Content);

string returnString = response.ToString();
Console.WriteLine(returnString);
Console.WriteLine(response.StatusCode);

我想打印要在控制台或其他格式上打印的内容类型信息。基本上我想在 c# 中查看内容类型。我该怎么做?

【问题讨论】:

  • 您是在寻找内容类型还是内容响应?

标签: c# .net rest httpresponse http-put


【解决方案1】:

通过使用存储在响应中的 Content.Headers.ContentType 信息 (Can't set Content-Type header on HttpResponseMessage headers?)。

例如,要将 Console-Type 写入控制台,您需要执行以下操作:

HttpResponseMessage response = await client.PutAsync("https://restapi.surveygizmo.com/v4/survey/2692209/surveypage/3/surveyquestion?", inputMessage.Content);

Console.WriteLine(response.Content.Headers.ContentType);

【讨论】:

    【解决方案2】:

    通过使用HttpContent 并读取缓冲区。

    表示 HTTP 实体主体和内容标头的基类。

    using (HttpContent content = response.Content)
    {
        // ... Read the string.
        string result = await content.ReadAsStringAsync();
    
        // ... Display the result.
        Console.WriteLine(result);
    }
    

    【讨论】:

    • 得到了我想要的答案,但后来我得到了这个异常 mscorlib.dll 中发生了“System.AggregateException”类型的未处理异常
    • 我希望您使用的是 result 变量,而不是重新运行 content.ReadAsStringAsync()
    • 是的,我正在使用结果变量。程序运行良好,我得到了答案,但之后我得到了异常我认为在这个地方的“System.AggregateException”类型的未处理异常 RunQuestions().Wait();
    • 看起来最初的问题已经满足,您应该打开一个新问题。祝你好运:)
    猜你喜欢
    • 2015-08-01
    • 2020-01-01
    • 2017-01-24
    • 2016-04-17
    • 1970-01-01
    • 2015-08-26
    • 2012-12-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多