微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

未在最终HTTP响应中添加自定义标头-AWS .NET Lambda SDK中的APIGatewayHttpApiV2ProxyResponse类 日志环境

如何解决未在最终HTTP响应中添加自定义标头-AWS .NET Lambda SDK中的APIGatewayHttpApiV2ProxyResponse类 日志环境

说明

我正在使用不带Amazon.Lambda.AspNetCoreServer软件包的AWS Lambda BUT,一切正常,除了我添加了一些基本的自定义响应标头(例如JSON内容类型)并且最终未添加任何内容之外HTTP响应标头。

在我的特定情况下,我没有使用Amazon.Lambda.AspNetCoreServer,因为我正在构建无服务器框架模板。

    public class GetUserByIdFunction : FunctionBase
    {
        private IUserRepository _userRepository;

        protected override void ConfigureServices(IServiceCollection serviceCollection)
        {
            var connString = Configuration["UserServiceDbContextConnectionString"];

            // serviceCollection.AddDbContext<UserContext>(options => options.UseMysqL(connString));
            serviceCollection.AddDbContext<UserContext>(options => options.UseInMemoryDatabase(connString));//temporarily

            serviceCollection.AddScoped<IUserRepository,UserRepository>();
        }

        protected override void Configure(IServiceProvider serviceProvider)
        {
            _userRepository = serviceProvider.GetService<IUserRepository>();
        }

        // Invoked by AWS Lambda at runtime
        public GetUserByIdFunction()
        {
        }

        public GetUserByIdFunction(
            IConfiguration configuration,IUserRepository userRepository)
        {
            // Constructor used by tests
            _userRepository = userRepository;
        }


        public async Task<APIGatewayHttpApiV2ProxyResponse> Handle(APIGatewayHttpApiV2ProxyRequest request,ILambdaContext context)
        {
            LogFunctionMetadata(request,context);

            if (!RunningAsLocal) ConfigureDependencies();

            var userId = Guid.Parse(request.PathParameters["userid"]);

            var user = await _userRepository.GetByIdAsync(userId);
            if (user == null) return NotFound();

            return Ok(user);
        }
    }
    public abstract class FunctionBase
    {
        protected IConfiguration Configuration { get; private set; }
        protected bool RunningAsLocal = false;

        public FunctionBase() => Configuration = ConfigurationService.Instance.Configuration;

        public FunctionBase(IConfiguration configuration)
        {
            Configuration = configuration;
            RunningAsLocal = true;
        }

        protected void ConfigureDependencies()
        {
            var serviceCollection = new ServiceCollection();
            ConfigureServices(serviceCollection);
            Configure(serviceCollection.BuildServiceProvider());
        }

        protected abstract void ConfigureServices(IServiceCollection serviceCollection);
        protected abstract void Configure(IServiceProvider serviceProvider);

        protected void LogFunctionMetadata(APIGatewayHttpApiV2ProxyRequest request,ILambdaContext context)
        {
            LambdaLogger.Log($"CONTEXT {Serialize(context.GetMainProperties())}");
            LambdaLogger.Log($"EVENT: {Serialize(request.GetMainProperties())}");
        }

        protected APIGatewayHttpApiV2ProxyResponse Ok() =>
            new APIGatewayHttpApiV2ProxyResponse()
            {
                StatusCode = (int) HttpStatusCode.OK,Headers = new Dictionary<string,string>
                {
                    {"Content-Type","application/json"}
                }
            };

        protected APIGatewayHttpApiV2ProxyResponse NotFound() =>
            new APIGatewayHttpApiV2ProxyResponse()
            {
                StatusCode = (int) HttpStatusCode.NotFound,"application/json"}
                }
            };
    }

唯一的问题是添加APIGatewayHttpApiV2ProxyResponse类的任何标头都没有按预期方式添加到最终HTTP响应中。

注意:我已经尝试使用它的SetHeaderValues,例如:

      protected APIGatewayHttpApiV2ProxyResponse Ok(object body)
        { 
            var response = new APIGatewayHttpApiV2ProxyResponse()
            {
                StatusCode = (int) HttpStatusCode.OK,Body = Serialize(body)
            };
            
            response.SetHeaderValues("Content-Type","application/json",false);
            response.SetHeaderValues("Access-Control-Allow-Origin","*",false);
            response.SetHeaderValues("Access-Control-Allow-Credentials","true",false);

            return response;
        }

复制步骤

git clone https://github.com/RichardSilveira/UserServerlessMicroservice cd UserServerlessMicroservice cd src/userService npm i -g serverless

注意:无服务器框架会在Cloudformation上创建一个抽象层,这意味着将一个堆栈部署到AWS账户中,您可以轻松删除该堆栈-您将在该堆栈上不收取任何费用。

provider:
  name: aws
  profile: default
  runtime: dotnetcore3.1
  stage: dev
  region: sa-east-1

您可以通过添加serverless.yml(例如上例中的示例)从profile: <name>文件中的本地计算机AWS凭证文件通知配置文件名称。这是可选的,如果不执行任何操作,将使用配置文件

build sls deploy -v

日志

不适用

环境

我认为最好展示我所有的项目描述文件

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles>
    <PackageId>aws-csharp</PackageId>
    <RootNamespace>UserService</RootNamespace>
  </PropertyGroup>

  <ItemGroup>
    <packagereference Include="Amazon.Lambda.APIGatewayEvents" Version="2.1.0" />
    <packagereference Include="Amazon.Lambda.Core" Version="1.1.0" />
    <packagereference Include="Amazon.Lambda.Serialization.SystemTextJson" Version="2.0.1" />
    <packagereference Include="EventStore.Client" Version="20.6.0" />
    <packagereference Include="FluentValidation" Version="9.0.1" />
    <packagereference Include="MediatR" Version="8.1.0" />
    <packagereference Include="MediatR.Extensions.Microsoft.DependencyInjection" Version="8.1.0" />
    <packagereference Include="Microsoft.EntityFrameworkCore.InMemory" Version="3.1.6" />
    <packagereference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.1.6" />
    <packagereference Include="Microsoft.Extensions.Configuration" Version="3.1.6" />
    <packagereference Include="Microsoft.Extensions.Configuration.Abstractions" Version="3.1.6" />
    <packagereference Include="Microsoft.Extensions.Configuration.Environmentvariables" Version="3.1.6" />
    <packagereference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="3.1.6" />
    <packagereference Include="Microsoft.Extensions.Configuration.Json" Version="3.1.6" />
    <packagereference Include="Microsoft.Extensions.DependencyInjection" Version="3.1.6" />
    <packagereference Include="MysqL.Data" Version="8.0.21" />
    <packagereference Include="Pomelo.EntityFrameworkCore.MysqL" Version="3.1.2" />
  </ItemGroup>

  <ItemGroup>
    <DotNetCliToolReference Include="Amazon.Lambda.Tools" Version="2.2.0" />
  </ItemGroup>

  <ItemGroup>
    <None Update="appsettings.json">
      <copyToOutputDirectory>Always</copyToOutputDirectory>
    </None>
    <None Update="appsettings.dev.json">
      <copyToOutputDirectory>Always</copyToOutputDirectory>
    </None>
    <None Update="appsettings.local.json">
      <copyToOutputDirectory>Always</copyToOutputDirectory>
    </None>
  </ItemGroup>

</Project>

有什么想法吗?

谢谢!

解决方法

您是否已将“ application / json”添加到API Gateway的媒体类型?还是那是默认的?我知道我必须添加“ application / octet-stream”。

,

已解决

按如下所示创建响应很好

input:-webkit-autofill,input:-webkit-autofill:hover,input:-webkit-autofill:focus,input:-webkit-autofill:active,input:-webkit-autofill::first-line {
  font-size: 18px;
}

而不是将其他词典分配给Headers属性

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。