Convert post data from webclient to httpclient

Viewed 33

I have searched and can't find an answer that is close to what how I need to convert webClient to HttpClient.

I have an xml file that is written to a memory stream and uploaded to a provider to post data. I get back a response as a byte array that is converted to an ascii string. It is some code I copied 10 years ago and have been using it until I went to upgrade my webapi to net 6.0. Then I discovered that webClient was deprecated.

Here is the code I need to convert:

public static string Submit(string url,other string fields){
MemoryStream stream = new MemoryStream();
XmlTextWriter xml = new XmlTextWriter(stream, null);
--here I add several xml nodes and data
WebClient web = new WebClient();
web.Credentials = CredentialCache.DefaultCredentials;
try
{
    byte[] response = web.UploadData(url, stream.ToArray());
    return Encoding.ASCII.GetString(response);

}
catch (WebException ex)
{
   if (((null != ex.Response)))
    {
       using (StreamReader reader = new StreamReader(ex.Response.GetResponseStream()))
       {
          return reader.ReadToEnd();
       }
    }
    return ex.ToString();
  }
}

Thanks in advance

1 Answers

This should get you started. This assumes an ASP.NET MVC Web API project, but the solution can be adapted to other project types:

Program.cs:

builder.Services.AddHttpClient("myClient")
    .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler()
    {
        UseDefaultCredentials = true
    });

Controller constructor:

private readonly IHttpClientFactory _httpClientFactory;

public MyController(IHttpClientFactory httpClientFactory)
{
      _httpClientFactory = httpClientFactory;   // inject it into the class
}

Controller (Submit is to be called from a separate Post action method):

using System.Text;
using System.Xml;

public async Task<string?> Submit(string url, other string fields)
{
    MemoryStream stream = new MemoryStream();
    XmlTextWriter xml = new XmlTextWriter(stream, null);
    //here I add several xml nodes and data
    var client = _httpClientFactory.CreateClient("myClient");
    string content = Encoding.ASCII.GetString(stream.ToArray());
    var httpContent = new StringContent(content, Encoding.UTF8, "text/xml");
    string? response = null;

    try
    {
        HttpResponseMessage result = await client.PostAsync(url, httpContent);
        response = await result.Content.ReadAsStringAsync();
    }
    catch
    {
        ...
    }

    return response;
}
Related