ASP.NET“直通”WEB API

木根

一:我目前正在與由兩個連接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(...)
        .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;
}
丹德里

尚未親自嘗試過,但您可以嘗試將來自內部 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);
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章