【问题标题】:Unable to deserialize the Web Api Core Response in a wcf service无法反序列化 wcf 服务中的 Web Api 核心响应
【发布时间】:2020-06-20 02:32:21
【问题描述】:

'WcfEntAdmin' 是 WcfService,它在内部调用 WebApi 核心服务来获取一些数据。我使用 HttpClient 来调用 WebApi Core 服务。调用成功返回 200 状态码,但是当我尝试反序列化响应时,应用程序进入中断状态。我不确定可能出了什么问题。

public class ApiHelper
{
private readonly JWTHandler _jwtHandler;
private readonly HttpClient _httpClient;
private readonly HttpClient _secureHttpClient;

public ApiHelper()
{
_httpClient = new HttpClient(ConfigureHandler());
_jwtHandler = new JWTHandler("myusername", "test", memoryCache, new AuthorizationClient(_configuration, _httpClient));
_jwtHandler.InnerHandler = ConfigureHandler();
_secureHttpClient = new HttpClient(_jwtHandler);
}

public bool IsAutoPolicy()
{
// the code here makes a call to the Web Api Core using the _securityHttpClient and determines if it's a Auto Policy or not 
}

public async Task<ApiVehiclesInfo> GetVehicleList(string policyNumber, DateTime effectiveDate)
{
    ApiVehiclesInfo vehiclesInfo = new ApiVehiclesInfo();
    if (IsPATEnabled())
    {
      var secureApiClient = new BaseApiClient(_configuration, _secureHttpClient);
      var response = await secureApiClient.GetAsync("PolicyApi",$"legacy_adapter/vehicles/{policyNumber}/{effectiveDate.ToString("yyyy-MMM-dd")}");
      if (response.IsSuccessStatusCode)
      {
          try
          {
            vehiclesInfo = await response.Deserialize<ApiVehiclesInfo>();
          }
          catch (Exception e)
          {
            Debug.WriteLine(e);
            throw;
          }
     }
  }
return vehiclesInfo;
}

调用代码首先调用IsAutoPolicy(),然后调用GetVehiclesList("1234567",DateTime.Now)

编辑:我将反序列化作为 HttpResponseMessage 的扩展方法

public static async Task<TResult> Deserialize<TResult>(this HttpResponseMessage response)
{
    try
    {
       using (Stream stream = await response.Content.ReadAsStreamAsync())
       using (StreamReader streamReader = new StreamReader(stream))
       using (JsonReader textReader = new JsonTextReader(streamReader))
       {
           JsonSerializer serializer = new JsonSerializer
           {
               NullValueHandling = NullValueHandling.Ignore,
               MissingMemberHandling = MissingMemberHandling.Ignore,
           };
        return serializer.Deserialize<TResult>(textReader);
        }
   }
    catch (Exception ex)
    {
        ex.Data.Add("StatusCode", response.StatusCode);
        ex.Data.Add("ReasonPhrase", response.ReasonPhrase);
        throw new SerializationException("Failed to deserialize", ex);
    }
}

【问题讨论】:

    标签: asp.net-core-webapi dotnet-httpclient


    【解决方案1】:

    当你从 api 返回响应时,你不能直接 反序列化响应。

    需要通过如下代码获取返回的json,然后反序列化:

     string responseString = await response.Content.ReadAsStringAsync();
     vehiclesInfo = Newtonsoft.Json.JsonConvert.DeserializeObject<ApiVehiclesInfo>(responseString);
    

    【讨论】:

    • 我编辑了问题以包含 Deserialize(this HttpResponseMessage response) 扩展方法的代码。即使那样,我也尝试了您提供的步骤。但我仍然得到休息状态
    猜你喜欢
    • 2011-09-13
    • 1970-01-01
    • 1970-01-01
    • 2012-05-20
    • 2012-09-20
    • 1970-01-01
    • 2019-01-04
    • 1970-01-01
    相关资源
    最近更新 更多