从 .net lambda 返回非 200 Http 状态 - 无需 API 网关

问题描述 投票:0回答:1

我正在尝试使用 amazon.lambda.core 从 .net 返回其他 http 状态代码 - 我尝试将其作为处理程序:

    public async Task<string> Handler(string input, ILambdaContext context)
    {
        await Task.FromResult(0);
        throw new AmazonLambdaException(Json.Serialize(new { error = "Your specific error message" }), ErrorType.Sender,
            "Bad Request", "abc", HttpStatusCode.BadRequest);
    }

但是当我从 python 客户端应用程序调用它时 - 我得到:

回应=

 {'RequestId': 'xxx', 'HTTPStatusCode': 200, 'HTTPHeaders': {'date': 'Thu, 07 Sep 2023 07:29:09 GMT', 'content-type': 'application/json', 'content-length': '1053', 'connection': 'keep-alive', 'x-amzn-requestid': 'xxxx', 'x-amz-function-error': 'Unhandled', 'x-amzn-remapped-content-length': '0', 'x-amz-executed-version': '$LATEST', 'x-amzn-trace-id': 'root=xxx;sampled=1;lineage=xxx:0'}, 'RetryAttempts': 0}, 'StatusCode': 200, 'FunctionError': 'Unhandled', 'ExecutedVersion': '$LATEST', 'Payload': <botocore.response.StreamingBody object at 0x0000021A6B813100>}

我想改变的关键是状态码 200 - 有可能吗?

注意 - 这张图片中没有涉及 api 网关 - 只是对 lambda 函数进行直接 http 调用的一件事(尽管在本例中我是从 boto3 调用它)

c# .net aws-lambda http-status-codes
1个回答
0
投票

我认为发生的情况是,从客户端的角度来看,调用执行正常,但在内部失败,并且您实际上没有返回任何内容!您只需在 Lambda 中抛出一个错误,该 Lambda 在一个小容器中运行。

查看文档 APIGatewayProxyResponse 他们返回以下内容:

var response = new APIGatewayHttpApiV2ProxyResponse
        {
            StatusCode = (int)HttpStatusCode.OK,
            Body = "Hello AWS Serverless",
            Headers = new Dictionary<string, string> { { "Content-Type",
"text/plain" } }
            };
            
            return response;
    }

所以你可以这样做:

public async Task<APIGatewayProxyResponse> Handler(APIGatewayProxyRequest request, ILambdaContext context)
{
    if (1 == 1) 
    {
        return new APIGatewayProxyResponse
        {
            StatusCode = 400,
            Body = "Something Bad happened with the request",
            Headers = new Dictionary<string, string> { { "Content-Type", "application/json" } }
        };
    }
}

您应该在 Lambda 的 CloudWatch 日志中获得一些提示(即您抛出的异常)。

更新

如果不涉及 API GW(我一开始没有完全注意到)并且您返回

string
,那么只需执行 Python 或 Node 的操作即可:

import json

def lambda_handler(event, context):
    return {
        'statusCode': 400,
        'body': json.dumps('BadRequest')
    }

控制台有点误导,看看这里是如何失败的,并且不返回 400。状态显示只有两种状态:成功和失败。有了 API GW,HTTP 概念就可以发挥更多作用。

© www.soinside.com 2019 - 2024. All rights reserved.