What is the best way to compose a rest PUT request in C#?
The request has to also send an object not present in the URI.
Sending a PUT Request with Axios The simplest way to make the PUT call is to simply use the put() function of the axios instance, and supply the body of that request in the form of a JavaScript object: const res = await axios. put('/api/article/123', { title: 'Making PUT Requests with Axios', status: 'published' });
So yes, a PUT request, technically, strictly, has to have a body.
You can send data to the server in the body of the HTTP PUT request. The type and size of data are not limited. But you must specify the data type in the Content-Type header and the data size in the Content-Length header fields. You can also post data to the server using URL parameters with a PUT request.
HTTP PUT sends data to a resource. The HTTP PUT request allows you to edit existing HTTP resources. The HTTP PUT method requests that the enclosed entity be stored under the supplied Request-URI. If the Request-URI refers to an already existing resource, it is modified.
using(var client = new System.Net.WebClient()) { client.UploadData(address,"PUT",data); }
My Final Approach:
public void PutObject(string postUrl, object payload) { var request = (HttpWebRequest)WebRequest.Create(postUrl); request.Method = "PUT"; request.ContentType = "application/xml"; if (payload !=null) { request.ContentLength = Size(payload); Stream dataStream = request.GetRequestStream(); Serialize(dataStream,payload); dataStream.Close(); } HttpWebResponse response = (HttpWebResponse)request.GetResponse(); string returnString = response.StatusCode.ToString(); } public void Serialize(Stream output, object input) { var ser = new DataContractSerializer(input.GetType()); ser.WriteObject(output, input); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With