Reputation: 175
I am upgrading a solution from .net core to .net 6.0 where i want to convert WebClient post method to HttpClient.Here is WebClient Post Code
request contains username and password
request= new
{
OsUsername = "abc",
OsPassword = "password"
}
private JObject Post(string path, object request)
{
string rawRequest = null;
string rawResponse = null;
try
{
using var client = new WebClient();
rawRequest = JsonConvert.SerializeObject(request, (Newtonsoft.Json.Formatting) Formatting.Indented);
rawResponse = client.UploadString(BaseUrl + path, "POST", rawRequest);
var response = JObject.Parse(rawResponse);
if (!path.StartsWith("resource"))
{
ValidateResponse(response);
}
return response;
}
catch (Exception)
{
Logger.Information(rawRequest);
Logger.Error(rawResponse);
throw;
}
}
i am writing following code and using HttpClient Post method
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("BaseUrl");
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("Username", "abc"),
new KeyValuePair<string, string>("Password", "password")
});
var result = await client.PostAsync(BaseUrl + url, content);
string resultContent = await result.Content.ReadAsStringAsync();
Console.WriteLine(resultContent);
}
but not getting weather above code is correct and also can i use send method instead of postasync method please suggest.
Upvotes: 2
Views: 674
Reputation: 78
Use an object of parameters like that instead of KeyValuePair
internal record User(string Name, string Password);
Then you can use a generic method
public async Task<TResult> Post<TResult>(string url, object data)
{
using var client = new HttpClient();
var content = JsonContent.Create(data);
var response = await client.PostAsync(url, content);
var result = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<TResult>(result);
}
Example of using:
var user = new User("abc", "password");
var result = await Post<Result>("https://url.com/", user);
Upvotes: 2