简体   繁体   中英

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

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM