简体   繁体   English

反序列化 HttpResponseMessage

[英]Deserialize HttpResponseMessage

I have an API (asp net core 3.1) and a web application (asp net Blazor WebAssembly).我有一个 API(asp net core 3.1)和一个 web 应用程序(asp net Blazor WebAssembly)。 In my API I have a CustomerController with the following method for POST:在我的 API 中,我有一个带有以下 POST 方法的 CustomerController:

    [HttpPost]
    public async
        Task<ActionResult>
        CreateOrderAsync(OrderDto orderDto)
    {
        orderDto.IdOrder =
            await repository
            .CreateOrderAsync(mapper.Map<Order>(orderDto));
        return CreatedAtRoute(nameof(GetOrderByIdAsync),
            new { idOrder = orderDto.IdOrder }, orderDto);
    }

In my web application I have the class DataServiceHelper, which I use in the actual data services for the web app.在我的 web 应用程序中,我有类 DataServiceHelper,我在 web 应用程序的实际数据服务中使用它。 Here I have methods for POST and GET and so on:这里我有 POST 和 GET 等方法:

  ...
  static public async Task PostAsync(HttpClient httpClient, string endpoint, T item)
  {
     await httpClient.PostAsJsonAsync(endpoint, item);
  }
  static public async Task<T> FindOneByIdAsync(HttpClient httpClient, string endpoint)
  {
      return await JsonSerializer.DeserializeAsync<T>
         (await httpClient.GetStreamAsync(endpoint), new JsonSerializerOptions()
         { ropertyNameCaseInsensitive = true });
  }
  ...

If I send a POST request to the API (say via Postman) the response contains (among others) the body, which is a jsonized version of my database object.如果我向 API 发送 POST 请求(比如通过 Postman),响应包含(除其他外)正文,它是我的数据库对象的 jsonized 版本。 Can I somehow catch that body in my Web App with JsonSerializer and return it like I do with my FindOneByIdAsync method?我可以使用 JsonSerializer 在我的 Web 应用程序中以某种方式捕获该主体并像使用 FindOneByIdAsync 方法一样返回它吗? Alternatively, in the API, could I create a new header in the responses headers that only contains the Id, that the database creates for the new object, and catch that in my web apps post method from the response?或者,在 API 中,我是否可以在仅包含 Id 的响应标头中创建一个新标头,该标头是数据库为新对象创建的,并在我的 Web 应用程序 post 方法中从响应中捕获它?

Might be a little cumbersome, but this works:可能有点麻烦,但这有效:

static public async Task<T>PostAndListenAsync(HttpClient httpClient, string endpoint, T item)
{            
    var content = await httpClient.PostAsJsonAsync(endpoint, item);
    var stream = await content.Content.ReadAsStreamAsync();
    T t = await JsonSerializer.DeserializeAsync<T>(stream, new JsonSerializerOptions() { PropertyNameCaseInsensitive = true });
    return t;
}

Feel free to make a neat one-liner out of it.随意用它做一个整洁的单线。

My Data Service:我的数据服务:

public async Task<OrderDto> PostOrderAsync(OrderDto orderDto)
{
    return await DataServiceHelper<OrderDto>.PostAndListenAsync(httpClient, "/Orders", orderDto);
}

In razor:在剃须刀中:

...
private async Task CreateNewOrder()
{
        OrderDto orderDto = await dataService.PostOrderAsync(newOrder);
}
...

Use System.Net.Http.Json .使用System.Net.Http.Json Examples:例子:

Task<O> CallGet<O>(string requestUrl) => http.GetFromJsonAsync<O>(requestUrl);

async Task<O> CallPost<I, O>(string requestUrl, I input)
{
    using var response = await http.PostAsJsonAsync(requestUrl, input);
    return await response.Content.ReadFromJsonAsync<O>();
}

See the documentation for more methods and overloads.有关更多方法和重载,请参阅文档。

It is available also as a nuget: https://www.nuget.org/packages/System.Net.Http.Json它也可以作为 nuget 使用: https ://www.nuget.org/packages/System.Net.Http.Json

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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