一:我目前正在與由兩個連接API的架構作業外部API暴露給客戶和內部API它連接到內部服務,并且只暴露于外部API。
在外部API應該是通過從回應資料的內部API給客戶端,而不處理,但我想不出來做到這一點。我目前正在反序列化和再次序列化物件。
這只是一個問題,因為對于大型 json 有效負載(大于 15MB),外部 API開始增加一些相當長的處理時間,這僅來自 json 反序列化方法。
有沒有辦法根據請求回傳一個json結果,而不處理它?
為簡潔起見,當前代碼已簡化:
外部 API 控制器
[HttpGet]
public async Task<ActionResult> GetSomeData(...)
{
var serviceResponse = await _serviceInvoker.GetAsync<SomeType>(...)
.ConfigureAwait(false);
Response.StatusCode = (int)serviceResponse.StatusCode;
return new JsonResult(serviceResponse.Content);
}
內部服務呼叫者回應決議器
using System.Text.Json;
private async Task<ServiceInvokerResult> ParseServiceResponse<T>(HttpResponseMessage response)
{
object deserializedContent = null;
var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
switch (response.StatusCode)
{
case HttpStatusCode.OK:
deserializedContent = JsonSerializer.Deserialize<T>(content);
break;
(...)
}
return new ServiceInvokerResult
{
(...)
StatusCode = response.StatusCode,
Content = deserializedContent ?? content
};
}
///
基于回應的解決方案更新:
該ServiceInvoker現在總是回傳HttpResponseMessage不處理它:
外部 API 控制器
[HttpGet]
public async Task<ActionResult> GetSomeData(...)
{
var serviceResponse = await _serviceInvoker.GetAsync<SomeType>(...)
.ConfigureAwait(false);
Response.StatusCode = (int)serviceResponse.StatusCode;
return new FileStreamResult(await response.GetContentAsStreamAsync(), response.GetContentType());
}
擴展方法
public static async Task<Stream> GetContentAsStreamAsync(this HttpResponseMessage response)
{
return await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
}
public static string GetContentType(this HttpResponseMessage response)
{
return response.Content?.Headers?.ContentType?.MediaType ?? Constants.Http.JsonContentType;
}
uj5u.com熱心網友回復:
尚未親自嘗試過,但您可以嘗試將來自內部 API 的資料流回傳給您的客戶端。
讓你的內部 API 回傳一個流:
private async Task<ServiceInvokerResult> ParseServiceResponse<T>(HttpResponseMessage response)
{
var contentStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
// ...
return new ServiceInvokerResult
{
(...)
StatusCode = response.StatusCode,
ContentStream = contentStream,
ContentType = "application/json"
};
}
然后,在您的外部 API 中:
[HttpGet]
public async Task<ActionResult> GetSomeData(...)
{
var response = await _serviceInvoker.GetContentStreamAsync(...)
.ConfigureAwait(false);
// ...
return File(response.ContentStream, response.ContentType);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/377704.html
