我应该使用StringContent类的目的是什么?

mtk*_*nko 17 c# asp.net-mvc

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

Lom*_*bas 14

StringContent类创建适合http服务器/客户端通信的格式化文本.在客户端请求之后,服务器将以a响应,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;
Run Code Online (Sandbox Code Playgroud)

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


Siv*_*ran 11

它基于字符串提供HTTP内容.

例:

在HTTPResponseMessage对象上添加内容

response.Content = new StringContent("Place response text here");
Run Code Online (Sandbox Code Playgroud)

  • @SivaCharan 它的目的是什么?什么时候会用到这个? (2认同)

Sho*_*din 8

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

    }
Run Code Online (Sandbox Code Playgroud)