How to set the content of an HttpWebRequest in C#?

后端 未结 5 1706
余生分开走
余生分开走 2020-12-03 09:47

An HttpWebRequest has the properties ContentLength and ContentType, but how do you actually set the content of the request?

5条回答
  •  醉梦人生
    2020-12-03 10:25

    .NET 4.5 (or .NET 4.0 by adding the Microsoft.Net.Http package from NuGet) provides a lot of additional flexibility in setting the request content. Here is an example:

    private System.IO.Stream Upload(string actionUrl, string paramString, Stream paramFileStream, byte [] paramFileBytes)
    {
        HttpContent stringContent = new StringContent(paramString);
        HttpContent fileStreamContent = new StreamContent(paramFileStream);
        HttpContent bytesContent = new ByteArrayContent(paramFileBytes);
        using (var client = new HttpClient())
        using (var formData = new MultipartFormDataContent())
        {
            formData.Add(stringContent, "param1", "param1");
            formData.Add(fileStreamContent, "file1", "file1");
            formData.Add(bytesContent, "file2", "file2");
            var response = client.PostAsync(actionUrl, formData).Result;
            if (!response.IsSuccessStatusCode)
            {
                return null;
            }
            return response.Content.ReadAsStreamAsync().Result;
        }
    }
    

提交回复
热议问题