更新时间:2024-04-12 GMT+08:00
分享

C#函数开发

函数定义

建议使用.NET Core 3.1版本。

对于C#,FunctionGraph运行时目前支持C#(.NET Core 2.1)、C#(.NET Core 3.1)、C#(.NET Core 6.0,当前仅支持华北-乌兰察布二零二)版本。

作用域 返回参数 函数名(函数参数,Context参数)

  • 作用域:提供给FunctionGraph调用的用户函数必须定义为public。
  • 返回参数:用户定义,FunctionGraph负责转换为字符串,作为HTTP Response返回。
  • 函数名:用户自定义函数名称,需要和函数执行入口处用户自定义的入口函数名称一致。

    在函数工作流控制台左侧导航栏选择“函数 > 函数列表”,单击需要设置的“函数名称”进入函数详情页,选择“设置 > 常规设置”,配置“函数执行入口”参数,如图1所示。其中参数值为“index.handler”格式,“index”和“handler”支持自定义命名。

    图1 函数执行入口参数
  • 执行事件体:函数执行界面由用户输入的执行事件参数。
  • 上下文环境(context):Runtime提供的函数执行上下文,相关属性定义在对象说明中。

    HC.Serverless.Function.Common –部署在FunctionGraph服务中的项目工程需要引入该库,其中包含IFunctionContext对象,详情见context类说明。

    创建csharp函数时,需要定义某个类中的方法作为函数执行入口,该方法可以通过定义IFunctionContext类型的参数来访问当前执行函数的信息。例如:

    1
    2
    3
    4
    public Stream handlerName(Stream input,IFunctionContext context)
    {
           // TODO
    }
    

函数Handler定义

ASSEMBLY::NAMESPACE.CLASSNAME::METHODNAME

  • .ASSEMBLY为应用程序的.NET程序集文件的名称,假设文件夹名称为HelloCsharp。
  • NAMESPACE、CLASSNAME即入口执行函数所在的namespace和class名称。
  • METHODNAME即入口执行函数名称。例如:

    创建函数时Handler:HelloCsharp::Example.Hello::Handler。

SDK接口

  • Context接口

    Context类中提供了许多属性供用户使用,如表1所示。

    表1 Context对象说明

    属性名

    属性说明

    String RequestId

    请求ID。

    String ProjectId

    Project Id

    String PackageName

    函数所在分组名称

    String FunctionName

    函数名称

    String FunctionVersion

    函数版本

    Int MemoryLimitInMb

    分配的内存。

    Int CpuNumber

    获取函数占用的CPU资源。

    String Accesskey

    获取用户委托的AccessKey(有效期24小时),使用该方法需要给函数配置委托。

    说明:

    当前函数工作流已停止维护Runtime SDK 中String AccessKey接口,您将无法使用String AccessKey获取临时AK。

    String Secretkey

    获取用户委托的SecretKey(有效期24小时),使用该方法需要给函数配置委托。

    说明:

    当前函数工作流已停止维护Runtime SDK 中String SecretKey接口,您将无法使用String SecretKey获取临时SK。

    String SecurityAccessKey

    获取用户委托的SecurityAccessKey(有效期24小时),使用该方法需要给函数配置委托。

    String SecuritySecretKey

    获取用户委托的SecuritySecretKey(有效期24小时),使用该方法需要给函数配置委托。

    String SecurityToken

    获取用户委托的SecurityToken(有效期24小时),使用该方法需要给函数配置委托。

    String Token

    获取用户委托的Token(有效期24小时),使用该方法需要给函数配置委托。

    Int RemainingTimeInMilliSeconds

    函数剩余运行时间

    String GetUserData(string key,string defvalue=" ")

    通过key获取用户通过环境变量传入的值。

  • 日志接口

    FunctionGraph中C# SDK中接口日志说明如所示。

    表2 日志接口说明

    方法名

    方法说明

    Log(string message)

    利用context创建logger对象:

    var logger = context.Logger;

    logger.Log("hello CSharp runtime test(v1.0.2)");

    Logf(string format, args ...interface{})

    利用context创建logger对象:

    var logger = context.Logger;

    var version = "v1.0.2"

    logger.Logf("hello CSharp runtime test({0})", version);

开发C#函数

如果是使用FunctionGraph服务提供的样例程序包fss_example_csharp2.0,请跳过12,直接执行3,并修改函数执行入口为:MyCsharpPro::src.Program::myFunc。

此处以Linux环境,C# (.NET Core 2.0)为例,开发C#函数步骤如下:

  1. 创建C#编译工程

    登录已经安装了.NET SDK和运行环境的linux服务器,创建目录“/home/fsscsharp/src”,将FunctionGraph函数dll解压到该目录。如图2所示。

    本文以fssCsharp2.0-1.0.1版本的dll函数为例,不同版本的dll无差异。
    图2 函数解压

    使用“dotnet --info”命令查看dotnet环境是否已安装,回显代码如下所示:

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    root@SZX1000371099:/home/fsscsharp/src# dotnet --info
    .NET Command Line Tools (2.1.202)
    
    Product Information:
     Version:            2.1.202
     Commit SHA-1 hash:  281caedada
    
    Runtime Environment:
     OS Name:     ubuntu
     OS Version:  14.04
     OS Platform: Linux
     RID:         ubuntu.14.04-x64
     Base Path:   /home/lusinking/dotnetdev/sdk/2.1.202/
    
    Microsoft .NET Core Shared Framework Host
    
      Version  : 2.0.9
      Build    : 1632fa1589b0eee3277a8841ce1770e554ece037
    

    创建并初始化console application工程,命令如下:

    “dotnet new console -n project_name”

    示例命令:

    dotnet new console -n MyCsharpPro

    在目录“/home/fsscsharp/src/MyCsharpPro”下的Program.cs代码文件中创建入口执行函数。其中input为客户端请求的body数据,context为FunctionGraph函数服务提供的运行时上下文对象,具体提供的属性可以参考属性接口。代码如下:

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    using HC.Serverless.Function.Common;
    using System;
    using System.IO;
    using System.Text;
    
    namespace src
    {
        class Program
        {
            static void Main(string[] args)
            {
                Console.WriteLine("Hello World!");
            }
            public Stream myFunc(Stream input,IFunctionContext context)
            {
                string payload = "";
                if (input != null && input.Length > 0)
                {
                    byte[] buffer = new byte[input.Length];
                    input.Read(buffer, 0, (int)(input.Length));
                    payload = Encoding.UTF8.GetString(buffer);
                }
                var ms = new MemoryStream();
                using (var sw = new StreamWriter(ms))
                {
                    sw.WriteLine("CSharp runtime test(v1.0.2)");
                    sw.WriteLine("=====================================");
                    sw.WriteLine("Request Id:       {0}", context.RequestId);
                    sw.WriteLine("Function Name:    {0}", context.FunctionName);
                    sw.WriteLine("Function Version: {0}", context.FunctionVersion);
                    sw.WriteLine("Project:          {0}", context.ProjectId);
                    sw.WriteLine("Package:          {0}", context.PackageName);
                    sw.WriteLine("Access Key:       {0}", context.AccessKey);
                    sw.WriteLine("Secret Key:       {0}", context.SecretKey);
                    sw.WriteLine("Token:            {0}", context.Token);
                    sw.WriteLine("User data(ud-a):  {0}", context.GetUserData("ud-a"));
                    sw.WriteLine("User data(ud-notexist): {0}", context.GetUserData("ud-notexist", ""));
                    sw.WriteLine("User data(ud-notexist-default): {0}", context.GetUserData("ud-notexist", "default value"));
                    sw.WriteLine("=====================================");
    
                    var logger = context.Logger;
                    logger.Logf("Hello CSharp runtime test(v1.0.2)");
                    sw.WriteLine(payload);
                }
                return new MemoryStream(ms.ToArray());
            }
        }
    }
    

    当函数的事件源是APIG时,相关约束条件请参考Base64解码和返回结构体的说明

  2. 编译C#工程

    手动在项目配置文件“MyCsharpPro.csproj”中添加FunctionGraph服务提供的dll引用(HinPath中填入dll的相对路径)。如下所示:

    <Project Sdk="Microsoft.NET.Sdk">
    
      <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>netcoreapp2.0</TargetFramework>
      </PropertyGroup>
      <ItemGroup>
        <Reference Include="HC.Serverless.Function.Common, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null">
          <HintPath>../HC.Serverless.Function.Common.dll</HintPath>
        </Reference>
      </ItemGroup>
    </Project>

    用“dotnet build”命令编译工程,回显信息如下:

    root@SZX1000371099:/home/fsscsharp/src/MyCsharpPro# vi MyCsharpPro.csproj
    root@SZX1000371099:/home/fsscsharp/src/MyCsharpPro# dotnet build
    Microsoft (R) Build Engine version 15.7.179.6572 for .NET Core
    Copyright (C) Microsoft Corporation. All rights reserved.
    
      Restore completed in 54.28 ms for /home/fsscsharp/src/MyCsharpPro/MyCsharpPro.csproj.
      MyCsharpPro -> /home/fsscsharp/src/MyCsharpPro/bin/Debug/netcoreapp2.0/MyCsharpPro.dll
    
    Build succeeded.
        0 Warning(s)
        0 Error(s)
    
    Time Elapsed 00:00:01.47

  3. 部署C#工程到FunctionGraph服务

    用ssh工具将编译后的文件拷贝并打包,如图3所示。
    图3 打包文件

    创建函数并上传上一步的zip包。

    执行函数,函数执行结果分为三部分,分别为函数返回(由callback返回)、执行摘要、日志输出(由Console.WriteLine()方法输出)。

执行结果

执行结果由3部分组成:函数返回、执行摘要和日志。

表3 执行结果说明

参数项

执行成功

执行失败

函数返回

返回函数中定义的返回信息。

返回包含错误信息和错误类型的JSON文件。格式如下:

{
    "errorMessage": "",
    "errorType": ""
}

errorMessage:Runtime返回的错误信息

errorType:错误类型

执行摘要

显示请求ID、配置内存、执行时长、实际使用内存和收费时长。

显示请求ID、配置内存、执行时长、实际使用内存和收费时长。

日志

打印函数日志,最多显示4KB的日志。

打印报错信息,最多显示4KB的日志。

分享:

    相关文档

    相关产品