![](/img/trans.png)
[英]How to get proper http status codes from Amazon API gateway integrated with C# lambda (not proxy integration)?
[英]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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.