I'm trying to send a request using http client. I need to add the body to the request and pass in parameters. I have some code based on http request but its not working currently:
httpClient.BaseAddress = new Uri(url);
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " token);
var value = JsonConvert.SerializeObject(obj);
var content = new StringContent(value, Encoding.UTF8, "application/json");
**var request = new HttpRequestMessage(new HttpMethod("PATCH"), url value);**
var response = await httpClient.SendAsync(request);
string Path = response.RequestMessage.RequestUri.AbsolutePath.ToString();
Success = response.IsSuccessStatusCode;
My issue is in the bold part of code. I need to be able to pass in that body portion some how to the request.
Current response: {StatusCode: 404, ReasonPhrase: 'Not Found', Version: 1.1, Content: System.Net.Http.StreamContent, Headers: { Transfer-Encoding: chunked Date: Tue, 29 Mar 2022 18:22:37 GMT Server: }}
So far not been able to find working code snippets for PATCH with body. I've even tried just doing a POST.
I've also tried this:
//httpClient.BaseAddress = new Uri(url);
//httpClient.DefaultRequestHeaders.Accept.Clear();
//httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//var s = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.MicrosoftDateFormat };
//var content = JsonConvert.SerializeObject(obj, s);
//var request = new HttpRequestMessage(new HttpMethod("PATCH"), url);
//request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
//var response = await httpClient.SendAsync(request);
//var responseString = await response.Content.ReadAsStringAsync();
//string Path = response.RequestMessage.RequestUri.AbsolutePath.ToString();
However, I noticed I ran into the same issue here as before. Its not adding the body to the request. I nuild it but never pass the body. So I need to pass the body in the request.
CodePudding user response:
All you need to do is set the Content
property of the HttpRequestMessage
:
var request = new HttpRequestMessage(HttpMethod.Patch, url) {
Content = new StringContent(value, Encoding.UTF8, "application/json")
};