[英]how to convert WebClient Post method to HttpClient in .net 6.0
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我正在将解决方案从 .net 核心升级到 .net 6.0,我想将 WebClient 发布方法转换为 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我正在编写以下代码并使用 HttpClient Post 方法
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.但没有得到上面代码的天气是正确的,我也可以使用发送方法而不是 postasync 方法请建议。
Use an object of parameters like that instead of KeyValuePair
使用类似参数的 object 而不是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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.