【问题标题】:Return File from AWS ApiGateway ASP.NET Core 3 Web API running as AWS Lambda function从作为 AWS Lambda 函数运行的 AWS ApiGateway ASP.NET Core 3 Web API 返回文件
【发布时间】:2020-11-07 16:56:25
【问题描述】:

我最近发现了能够在 AWS API Gateway (https://aws.amazon.com/blogs/developer/deploy-an-existing-asp-net-core-web-api-to-aws-lambda/) 后面运行 ASP.NET Core 3 - Web API 项目作为单个 Lambda 函数部署的魔力。我已经成功地通过浏览器和 Postman 部署并与我的项目的 API 交互——点击返回单个值或序列化为 JSON 的 C# 对象的响应的 API。我专门使用无服务器框架 (https://www.serverless.com/) 在我的帐户中部署解决方案。

但是,当将端点添加到我的控制器以提供静态文件时,特别是作为项目一部分的图像(捆绑在我的部署包中) - 我在本地运行时得到 HTTP 200 OK,并且文件和 HTTP 200 OK 但正文为空。对已部署 API Gateway 端点的后续请求返回 HTTP 304,但仍为空正文。

由于控制器上的方法在本地成功地提供文件,我认为当解决方案通过 API Gateway 部署为 Lambda 函数时,可能会有一些额外的配置或限制。

我尝试了几种不同的方法,但以下方法在本地有效,但在部署到 AWS 时无效。

    [HttpGet("Image2")]
    public IActionResult GetImage2()
    {
        string imagePath = "assets/baby-yoda.jpg";
        byte[] imageBytes = System.IO.File.ReadAllBytes(imagePath);
        return PhysicalFile(Path.Join(Directory.GetCurrentDirectory(), imagePath), "image/jpeg", "image.jpg");
    }

我的 serverless.yml 已更新为包括:

provider:
    apiGateway:
        binaryMediaType:
        - '*/*

现在,当端点被击中时,浏览器会下载文件 - 但是,文件似乎比原始文件大(429kb vs 324kb)并且已损坏/无法打开(“看起来像我们不支持这种文件格式。”

【问题讨论】:

  • 此 API 调用的无服务器 yml 配置是什么?我认为您应该首先查找该配置,以了解如何设置返回文件的 API。
  • 从 serverless.yml 文件提供 ApiGateway 详细信息/更新。
  • 您好,您对此有什么解决方案吗?

标签: c# asp.net-core aws-lambda aws-api-gateway asp.net-core-webapi


【解决方案1】:

在 LambdaEntryPoint 类的 Init() 方法(您向 AWS Lambda 注册为您的 Lambda 函数的“处理程序”的方法)上,我们需要添加一些额外的注册调用以将文件格式(内容类型)列入白名单在返回 API 网关之前应该序列化为 Base64。

namespace ProjectNameHere
{
    public class LambdaEntryPoint : Amazon.Lambda.AspNetCoreServer.APIGatewayProxyFunction
    {
        protected override void Init(IWebHostBuilder builder)
        {

            RegisterResponseContentEncodingForContentType("image/jpeg", ResponseContentEncoding.Base64);
            RegisterResponseContentEncodingForContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", ResponseContentEncoding.Base64);
            RegisterResponseContentEncodingForContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document", ResponseContentEncoding.Base64);

            builder
                .UseStartup<Startup>();
        }
    }
}

那么你的Controllers就可以通过ActionResult(File、FileStreamResult、FileContentResult等)通过正常的方式返回File:

[HttpGet("File")]
public async Task<ActionResult> File()
{
    try
    {
        var requestedFile = FileDictionary[1];
        return File(requestedFile.Bytes, requestedFile.MimeType);
    }
    catch (Exception ex)
    {
        _logger.LogError(ex.Message);
        _logger.LogError(ex.InnerException?.Message);
        return BadRequest();
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-28
    • 2019-03-30
    • 2023-01-11
    • 2022-11-18
    • 1970-01-01
    • 2021-08-24
    相关资源
    最近更新 更多