简体   繁体   English

我们可以使用无服务器框架将 a.Net Core 3 服务部署到 AWS Lambda 吗?

[英]Can we deploy a .Net Core 3 service to AWS Lambda using the Serverless Framework?

Now that.Net Core 3 has dropped and AWS announced Custom Runtimes, I'm looking to take advantage of some of the new.Net Core 3 features.现在 .Net Core 3 已经放弃,AWS 宣布了自定义运行时,我希望利用一些新的 .Net Core 3 功能。 Unfortunately, I'm coming up short when trying to find information on how to do this using the Serverless Framework.不幸的是,我在尝试查找有关如何使用无服务器框架执行此操作的信息时遇到了问题。 Has anyone out there done this yet?有没有人做过这个? And if so, is there a good online resource on how to do so?如果是这样,是否有一个很好的在线资源来说明如何做到这一点?

The short answer is 'yes'.简短的回答是“是”。

Amazon state:亚马逊 state:

The Lambda team's policy is to support Long Term Support (LTS) versions of a runtime so .NET Core 3.0 will not be natively supported on AWS Lambda. Lambda 团队的政策是支持运行时的长期支持 (LTS) 版本,因此 AWS Lambda 将不会原生支持 .NET Core 3.0。

That doesn't mean you can't use .NET Core 3.0 on Lambda today though.这并不意味着您今天不能在 Lambda 上使用 .NET Core 3.0。 With the Amazon.Lambda.RuntimeSupport NuGet package you can use any version of .NET Core including 3.0.使用 Amazon.Lambda.RuntimeSupport NuGet package,您可以使用任何版本的 Z303CB0EF9EDB9082ZD61BBBE3508。 This is possible because one of the great features of .NET Core is the ability to package up an application as a completely self contained deployment bundle.这是可能的,因为 .NET Core 的一大特点是能够将 package 应用程序作为一个完全独立的部署包。 The following blog post shows how to use Amazon.Lambda.RuntimeSupport.以下博客文章展示了如何使用 Amazon.Lambda.RuntimeSupport。 https://aws.amazon.com/blogs/developer/announcing-amazon-lambda-runtimesupport/ https://aws.amazon.com/blogs/developer/announcing-amazon-lambda-runtimesupport/

We have successfully deployed a.Net Core 3.0 Web Api to AWS Serverless.我们已成功将 a.Net Core 3.0 Web Api 部署到 AWS Serverless。

Here's how I did it:我是这样做的:

  1. Added NuGet packages:添加了 NuGet 包:
 Amazon.Lambda.AspNetCoreServer 
 Amazon.Lambda.RuntimeSupport
  1. Added Lambda entry point添加了 Lambda 入口点
    public class LambdaEntryPoint :
        // When using an ELB's Application Load Balancer as the event source change 
        // the base class to Amazon.Lambda.AspNetCoreServer.ApplicationLoadBalancerFunction
        Amazon.Lambda.AspNetCoreServer.APIGatewayProxyFunction
    {
        /// <summary>
        /// The builder has configuration, logging and Amazon API Gateway already configured. The startup class
        /// needs to be configured in this method using the UseStartup<>() method.
        /// </summary>
        /// <param name="builder"></param>
        protected override void Init(IWebHostBuilder builder)
        {
            builder.UseStartup<Startup>();
        }
    }
  1. Updated Main function更新主 function
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Amazon.Lambda.Core;
using Amazon.Lambda.APIGatewayEvents;
using Amazon.Lambda.RuntimeSupport;
using Amazon.Lambda.Serialization.Json;

namespace CustomRuntimeAspNetCore30
{
    public class Program
    {

        public static void Main(string[] args)
        {
            if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("AWS_LAMBDA_FUNCTION_NAME")))
            {
                CreateHostBuilder(args).Build().Run();
            }
            else
            {
                var lambdaEntry = new LambdaEntryPoint();
                var functionHandler = (Func<APIGatewayProxyRequest, ILambdaContext, Task<APIGatewayProxyResponse>>)(lambdaEntry.FunctionHandlerAsync);
                using (var handlerWrapper = HandlerWrapper.GetHandlerWrapper(functionHandler, new JsonSerializer()))
                using (var bootstrap = new LambdaBootstrap(handlerWrapper))
                {
                    bootstrap.RunAsync().Wait();
                }
            }
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }
}
  1. Added serverless.template file:添加了 serverless.template 文件:
{
  "AWSTemplateFormatVersion": "2010-09-09",
  "Transform": "AWS::Serverless-2016-10-31",
  "Description": "An AWS Serverless Application that uses the ASP.NET Core framework running in Amazon Lambda.",
  "Parameters": {},
  "Conditions": {},
  "Resources": {
    "AspNetCoreFunction": {
      "Type": "AWS::Serverless::Function",
      "Properties": {
        "Handler": "not-required",
        "Runtime": "provided",
        "CodeUri": "",
        "MemorySize": 256,
        "Timeout": 30,
        "Role": null,
        "Policies": [
          "AWSLambdaFullAccess"
        ],
        "Environment": {
          "Variables": {
            "LAMBDA_NET_SERIALIZER_DEBUG": "true"
          }
        },
        "Events": {
          "ProxyResource": {
            "Type": "Api",
            "Properties": {
              "Path": "/{proxy+}",
              "Method": "ANY"
            }
          },
          "RootResource": {
            "Type": "Api",
            "Properties": {
              "Path": "/",
              "Method": "ANY"
            }
          }
        }
      }
    }
  },
  "Outputs": {
    "ApiURL": {
      "Description": "API endpoint URL for Prod environment",
      "Value": {
        "Fn::Sub": "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/"
      }
    }
  }
}
  1. Added aws-lambda-tools-defaults.json添加了 aws-lambda-tools-defaults.json
{
  "Information": [
    "This file provides default values for the deployment wizard inside Visual Studio and the AWS Lambda commands added to the .NET Core CLI.",
    "To learn more about the Lambda commands with the .NET Core CLI execute the following command at the command line in the project root directory.",
    "dotnet lambda help",
    "All the command line options for the Lambda command can be specified in this file."
  ],
  "profile": "default",
  "region": "",
  "configuration": "Release",
  "s3-prefix": "CustomRuntimeAspNetCore30/",
  "template": "serverless.template",
  "template-parameters": "",
  "msbuild-parameters": "--self-contained true /p:AssemblyName=bootstrap",
  "framework": "netcoreapp3.0",
  "s3-bucket": "",
  "stack-name": "CustomRuntimeAspNetCore30"
}
  1. Turned on Visual Studio deployment wizard.打开 Visual Studio 部署向导。

Edit the project file to include the AWSProjectType with a value of Lambda in the PropertyGroup collection.编辑项目文件以在 PropertyGroup 集合中包含值为 Lambda 的 AWSProjectType。

<PropertyGroup>
  <TargetFramework>netcoreapp3.0</TargetFramework>
  <AWSProjectType>Lambda</AWSProjectType>
</PropertyGroup>

You can then deploy the ASP.NET Core project to Lambda by right-clicking the project in Visual Studio and selecting 'Publish to AWS Lambda...'然后,您可以通过在 Visual Studio 中右键单击项目并选择“发布到 AWS Lambda...”,将 ASP.NET 核心项目部署到 Lambda...

More info here:更多信息在这里:

https://aws.amazon.com/blogs/developer/net-core-3-0-on-lambda-with-aws-lambdas-custom-runtime/ https://aws.amazon.com/blogs/developer/net-core-3-0-on-lambda-with-aws-lambdas-custom-runtime/

Note that this process may error if the webapi project you are publishing has references to other assemblies.请注意,如果您发布的 webapi 项目引用了其他程序集,则此过程可能会出错。 This is because in the deployment (step 5), it attempts to rename all assemblies to 'bootstrap'.这是因为在部署(步骤 5)中,它尝试将所有程序集重命名为“引导程序”。 then you will need to:那么您将需要:

Rename your project's assembly name in the csproj file to 'bootstrap' (without quotes).将 csproj 文件中项目的程序集名称重命名为“bootstrap”(不带引号)。 Modify aws-lambda-tools-defaults.json so that the line:修改 aws-lambda-tools-defaults.json 使该行:

"msbuild-parameters": "--self-contained true /p:AssemblyName=bootstrap",

becomes变成

"msbuild-parameters"  : "--self-contained true",

Note also that logging seems to have changed from.Net 2.1.另请注意,日志记录似乎已从 .Net 2.1 更改。

I tried to implement logging as per.Net Core 2.1.我尝试按照.Net Core 2.1 实现日志记录。 That is:那是:

    public static IHostBuilder CreateHostBuilder(string[] args) =>
       Host.CreateDefaultBuilder(args)
         .ConfigureLogging(logging =>
         {
            logging.AddAWSProvider();
            logging.SetMinimumLevel(LogLevel.Debug);
         })
         .ConfigureWebHostDefaults(webBuilder =>
         {
            webBuilder.UseStartup<startup>();
         });

(and similar code in LambdaEntryPoint.cs) (以及 LambdaEntryPoint.cs 中的类似代码)

However, this doesn't work.但是,这不起作用。 Looking at the code, it is trying to find the IConfiguration ImplementationInstance and this is null.查看代码,它试图找到 IConfiguration ImplementationInstance,这是 null。

According to this https://github.com/aspnet/AspNetCore/issues/14400 , this breaking change is by design.根据此https://github.com/aspnet/AspNetCore/issues/14400 ,此重大更改是设计使然。

To get logging working in.Net Core 3, you need to add code to Startup.Configure():要在.Net Core 3 中进行日志记录,您需要向 Startup.Configure() 添加代码:

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
        {
            var loggingConfigSection = Configuration.GetAWSLoggingConfigSection();
            var awsLoggerProvider = new AWSLoggerProvider(loggingConfigSection);
            loggerFactory.AddProvider(awsLoggerProvider);

            // rest of code
        }

暂无
暂无

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

相关问题 如何使用无服务器框架将 Streamlit(前端)Web 应用程序部署到 AWS Lambda? - How to deploy a Streamlit (frontend) webapp to AWS Lambda using Serverless Framework? 无服务器:无法使用部署命令在 AWS 上加载 lambda 函数 - Serverless: can't load lambda function on the AWS using deploy comand AWS Lambda-使用.NET Core构建无服务器API - AWS Lambda - Building serverless API using .NET Core aws lambda function 使用 asp.net 核心的无服务器模板 - aws lambda function using serverless template of asp.net core 无法使用无服务器框架在AWS Lambda中部署Node.js应用程序 - Cannot deploy Node.js app inside AWS Lambda using Serverless Framework 我可以在 AWS Lambda 上使用 .Net Framework 4.5 部署 RESTful API 吗? - Can I deploy a RESTful API with .Net Framework 4.5 on AWS Lambda? 如何使用适用于AWS Lambda的无服务器部署来部署环境变量 - How to deploy environment variable using serverless deploy for AWS lambda 将aws-serverless-express与node js一起使用时,我们可以创建多个aws lambda函数吗? - can we create multiple aws lambda function when using aws-serverless-express with node js 我们可以在Aws Lambda上部署Splash吗? - Can we deploy Splash on Aws Lambda? 如何使用 asp.net core 3.1 serverless 在 AWS lambda 中为复杂的配置参数设置环境变量? - How to set environment variables for complex configuration parameters in AWS lambda using asp.net core 3.1 serverless?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM