C# 我应该将 StringContent 类用于什么目的?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19479177/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 15:06:08  来源:igfitidea点击:

What purposes should I use class StringContent for?

c#asp.net-mvc

提问by mtkachenko

There is StringContent classin System.Net.Http namespace. What purposes should I use class StringContent for?

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

采纳答案by Siva Charan

It provides HTTP content based on a string.

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

Example:

例子:

Adding the content on HTTPResponseMessage Object

在 HTTPResponseMessage 对象上添加内容

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

回答by Nenad

Every response that is basically text encoded can be represented as StringContent.

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

Html reponse is text too (with proper content type set):

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

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

On the other side, if you download/upload file, that is binary content, so it cannot be represented by string.

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

回答by Lombas

StringContent class creates a formatted text appropriate for the http server/client communication. After a client request, a server will respond with a HttpResponseMessageand that response will need a content, that can be created with the StringContentclass.

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

Example:

例子:

 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;

In this example, the server will respond with the content present on the csvvariable.

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

回答by Liam

Whenever I want to send an object to web api server I use StringContent to add format to HTTP content, for example to add Customer object as json to server:

每当我想将对象发送到 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;

    }