繁体   English   中英

如何使用 AWS Gateway 获取 Lambda 以在 C# 中返回 HTTP 错误状态代码

[英]How can I get a Lambda using AWS Gateway to return HTTP error status code in C#

我正在尝试通过我的 AWS Gateway 返回状态错误代码(例如 500、400、401),但似乎无法弄清楚。

我看过一些例子,他们做了类似的事情:

return context.fail('Bad Request: You submitted invalid input');

但是, ILambdaContext对象上没有失败或成功方法。

这是我到目前为止所得到的(非工作)

拉姆达代码:

 var addressresponse = new AddressValidationResponse();
            addressresponse.Errors = new string[1];
            addressresponse.Errors[0] = "test error";
            addressresponse.Reason = "client_error";

 return addressresponse;

自定义错误模型

整合响应

方法响应

我想我已经接近了,但我仍然得到了 200 的回复,回复如下:

{
  "Reason": "client_error",
  "Errors": [
    "test error"
  ]
}

我在这里想念什么?

您需要在 C# lambda 函数中引发异常,并使用 API 网关控制台将特定错误代码映射到响应映射模板中的 HTTP 响应代码。

您可以使用 APIGatewayHttpApiV2ProxyResponse 来包装您的响应,如下所示:

public static async Task<APIGatewayHttpApiV2ProxyResponse?> FunctionHandler(APIGatewayHttpApiV2ProxyRequest request, ILambdaContext context)
{
    var response = new APIGatewayHttpApiV2ProxyResponse();
    try
    {
        response.Body = await DoSomeWorkAsync();
        response.StatusCode = (int)HttpStatusCode.OK;
    }
    catch (Exception ex)
    {
        response.StatusCode = (int)HttpStatusCode.InternalServerError;
        response.Body = JsonSerializer.Serialize(new { error = ex.Message }) ;
    }

    return response;
}

在这里回答了类似的问题

基本上,您需要返回 APIG 识别的响应对象。

这里有 C# 示例

我会说我在上下文 Lambda 中不使用 C#,基本上你需要返回标头、状态代码和响应正文。

暂无
暂无

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

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