her*_*ken 1 c# asp.net-web-api asp.net-core blazor blazor-webassembly
我有一个 API (asp net core 3.1) 和一个 Web 应用程序 (asp net Blazor WebAssembly)。在我的 API 中,我有一个 CustomerController,其 POST 方法如下:
[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);
}
Run Code Online (Sandbox Code Playgroud)
在我的 Web 应用程序中,我有 DataServiceHelper 类,我在 Web 应用程序的实际数据服务中使用它。这里我有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 });
}
...
Run Code Online (Sandbox Code Playgroud)
如果我向 API 发送 POST 请求(例如通过 Postman),则响应包含(除其他外)正文,它是我的数据库对象的 json 化版本。我能否以某种方式使用 JsonSerializer 在我的 Web 应用程序中捕获该正文并像使用 FindOneByIdAsync 方法一样返回它?或者,在 API 中,我可以在响应标头中创建一个仅包含数据库为新对象创建的 Id 的新标头,并在我的 Web 应用程序 post 方法中从响应中捕获该标头吗?
使用System.Net.Http.Json。例子:
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>();
}
Run Code Online (Sandbox Code Playgroud)
有关更多方法和重载,请参阅文档。
它也可以作为 nuget 提供:https ://www.nuget.org/packages/System.Net.Http.Json