I have this REST request; I'm trying to convert it to HttpClient
. I don't want to use RestSharp
in my application.
I'm not sure how to send over an empty body in the request: I keep getting "bad request" when I send a response.
Basically, I call a post
method to log in a user below. It works in RestSharp, but the request needs an empty body to be successful.
var client = new RestClient(Token.Location + "/users/api/login");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", Token.Value);
request.AddHeader("Content-Type", "application/json");
request.AddJsonBody(JsonSerializer.Serialize(new { }));
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
I'm trying to convert this piece of code to use HttpClient
in .net core 3.1.
Here is what I have tried:
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Authorization", Token.Value);
var stringContent = new StringContent(string.Empty);
var res = await client.PostAsync(Token.Location + "/users/api/login", stringContent);
var data = await res.Content.ReadAsStringAsync();
I've also tried
...
var content = new StringContent(JsonSerializer.Serialize(new { }), Encoding.UTF8, "application/json");
var res = await client.PostAsync(Token.Location + "/users/api/login", content);
...
var res = await client.PostAsync(Token.Location + "/users/api/login", null);
...
var res = await client.PostAsync(Token.Location + "/users/api/login", "Empty string");
I keep getting "bad request" because I'm not sending over an empty body.
I've tried in postman and it works with an empty raw body of {}
. What am I missing here?