【问题标题】:What purposes should I use class StringContent for?我应该将 StringContent 类用于什么目的?
【发布时间】:2013-10-29 00:56:51
【问题描述】:

System.Net.Http 命名空间中有StringContent class。我应该将 StringContent 类用于什么目的?

【问题讨论】:

  • 你可以阅读方法。
  • 别管它。如果您在 System.Net.Http 命名空间中遇到另一个使用 StringContent 类型的类型,那么您也会知道它的用途是什么......

标签: c# asp.net-mvc


【解决方案1】:

StringContent 类创建适合于 http 服务器/客户端通信的格式化文本。在客户端请求之后,服务器将使用 HttpResponseMessage 进行响应,并且该响应需要一个可以使用 StringContent 类创建的内容。

例子:

 string csv = "content here";
 var response = new HttpResponseMessage();
 response.Content = new StringContent(csv, Encoding.UTF8, "text/csv");
 response.Content.Headers.Add("Content-Disposition", 
                              "attachment; 
                              filename=yourname.csv");
 return response;

在此示例中,服务器将使用 csv 变量上的内容进行响应。

【讨论】:

    【解决方案2】:

    它提供基于字符串的 HTTP 内容。

    示例:

    在 HTTPResponseMessage 对象上添加内容

    response.Content = new StringContent("Place response text here");
    

    【讨论】:

    • 你能给我举个例子吗?
    • @oblomov:提供了一个例子
    • @SivaCharan 它的目的是什么?什么时候会用这个?
    • 我猜 StringContent 不支持像 \r\n 这样的转义字符。我在我的字符串中传递这些字符,但由于某种原因它失败了@SivaCharan
    • @SivaCharan,我确实检索字符串客户端?我不能
    【解决方案3】:

    每当我想向 Web api 服务器发送对象时,我都会使用 StringContent 向 HTTP 内容添加格式,例如将 Customer 对象作为 json 添加到服务器:

     public void AddCustomer(Customer customer)
        {
            String apiUrl = "Web api Address";
            HttpClient _client= new HttpClient();
    
            string JsonCustomer = JsonConvert.SerializeObject(customer);
            StringContent content = new StringContent(JsonCustomer, Encoding.UTF8, "application/json");
            var response = _client.PostAsync(apiUrl, content).Result;
    
        }
    

    【讨论】:

      【解决方案4】:

      基本上是文本编码的每个响应都可以表示为StringContent

      Html 响应也是文本(设置了正确的内容类型):

      response.Content = new StringContent("<html><head>...</head><body>....</body></html>")
      

      另一方面,如果你下载/上传文件,也就是二进制内容,所以不能用字符串表示。

      【讨论】:

        猜你喜欢
        • 2019-06-19
        • 1970-01-01
        • 2017-06-12
        • 1970-01-01
        • 2015-05-06
        • 2014-07-27
        • 2013-08-21
        • 2022-01-18
        • 2017-01-28
        相关资源
        最近更新 更多