我应该用StringContent类来达到什么目的?

42
在 System.Net.Http 命名空间中有 StringContent class 类。我应该使用 StringContent 类的哪些目的?

1
你可以阅读这些方法。 - gdoron
3
不要在意它。如果你遇到了System.Net.Http命名空间中使用StringContent类型的另一种类型,那么你也会知道它的用途是什么。 - user2819245
请参见无法找到如何使用HttpContent - Michael Freidgeim
4个回答

29

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 变量所包含的内容。

22

根据一个字符串提供HTTP内容。

例子:

将内容添加到HTTPResponseMessage对象上。

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

你能给我一个使用的例子吗? - mtkachenko
@oblomov:提供了一个例子。 - Siva Charan
2
@SivaCharan 它的目的是什么?什么情况下会使用它? - Robert Kerr
我猜StringContent不支持像\r\n这样的转义字符。我在我的字符串中传递这些字符,但出于某种原因它失败了@SivaCharan - aMazing
@SivaCharan,我能在客户端检索字符串吗?我现在做不到。 - Simone

7
每当我想向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;

    }

最佳实践是不要为每个请求创建一个新的 HttpClient :) - Nora
@Nora 嗯,HttpFactory 现在非常性感和有趣! - Shojaeddin

3

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

HTML响应也是文本(设置了适当的内容类型):

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

另一方面,如果您下载/上传文件,那么这是二进制内容,因此无法用字符串表示。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接