【问题标题】:ASP.NET Core 5 httpclient using xml使用 xml 的 ASP.NET Core 5 httpclient
【发布时间】:2021-12-31 18:29:15
【问题描述】:

httpClient 与 XML 一起使用来发帖和接听电话的首选方式是什么?

public class ShippingService : IShippingService
{
    private readonly HttpClient _httpClient;
    private readonly string _remoteServiceBaseUrl;

    public CatalogService(HttpClient httpClient)
    {
        _httpClient = httpClient;
    }

    public async Task<List<ShippingPrice>> GetShippingPrices()
    {
         // httpClient post using xml format
    }
}

【问题讨论】:

  • 使用IHttpClientFactory

标签: asp.net asp.net-core


【解决方案1】:

检查一下:

   HttpClient _httpClient = new HttpClient();
   string xml = ""; //serialize your object
   var content = new StringContent(xml, Encoding.UTF8, "application/xml");
   await _httpClient.PostAsync("http://example.com/api",content);

要将对象序列化为 xml,请参见:XML Serialize generic list of serializable objects

【讨论】:

  • 使用IHttpClientFactory而不是直接初始化HttpClient
  • 并且不要使用 _underscore 作为局部变量名称 - 已建立的约定为字段使用 _ 前缀(通常也只使用 static 字段)。对本地人使用 _ 违反了我所知道的所有惯例。
  • 你需要从PostAsync处理掉HttpResponseMessage
猜你喜欢
  • 1970-01-01
  • 2021-11-02
  • 2019-09-14
  • 2021-02-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多