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

后端 未结 5 1707
余生分开走
余生分开走 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:09

    Here's a different option for posting info without messing with Bytes and Streams. I personally find it easier to follow, read, and debug.

    // Convert Object to JSON
    var requestMessage = JsonConvert.SerializeObject(requestObject);
    var content = new StringContent(requestMessage, Encoding.UTF8, "application/json");
    
    // Create the Client
    var client = new HttpClient();
    client.DefaultRequestHeaders.Add(AuthKey, AuthValue);
    
    // Post the JSON
    var responseMessage = client.PostAsync(requestEndPoint, content).Result;
    var stringResult = responseMessage.Content.ReadAsStringAsync().Result;
    
    // Convert JSON back to the Object
    var responseObject = JsonConvert.DeserializeObject(stringResult);
    

提交回复
热议问题