全部产品
Search
文档中心

Function Compute:Kompilasi dan terapkan paket kode

更新时间:Jul 06, 2025

Anda dapat mengompilasi program dalam lingkungan .NET lokal, mengemasnya ke dalam paket ZIP, lalu mengunggah paket kode di konsol Function Compute atau menggunakan Serverless Devs. Setelah itu, Anda dapat menguji fungsi untuk memastikan kode berjalan sesuai harapan.

Pustaka dependensi untuk lingkungan runtime C#

Function Compute menyediakan pustaka dependensi Aliyun.Serverless.Core untuk runtime C#. Pustaka ini digunakan untuk mendefinisikan informasi seperti antarmuka handler dan objek konteks.

Anda dapat memperoleh pustaka dependensi dari NuGet dan menambahkannya ke file <NamaProyekAnda>.csproj di direktori kode. Contoh kode berikut memberikan ilustrasi:

  <ItemGroup>
        <PackageReference Include="Aliyun.Serverless.Core" Version="1.0.1" />
        <PackageReference Include="Aliyun.Serverless.Core.Http" Version="1.0.3" />
  </ItemGroup>

Gunakan .NET Core CLI untuk mengompilasi dan menerapkan program

Paket penyebaran .NET Core harus mencakup assembly yang dikompilasi dengan fungsi Anda dan semua dependensinya. Anda dapat menggunakan .NET Core CLI untuk mengompilasi dan menerapkan program. Dengan .NET Core CLI, Anda dapat membuat aplikasi Function Compute berbasis .NET lintas platform. Untuk informasi lebih lanjut, lihat .NET.

Langkah 1: Buat proyek .NET

  1. Jalankan perintah berikut untuk membuat proyek .NET:

    dotnet new console -o HelloFcApp -f netcoreapp3.1

    Berikut adalah parameter dalam perintah sebelumnya:

    • new console: Template aplikasi konsol.

    • -o|--output: Jalur keluaran proyek. Dalam contoh ini, direktori HelloFcApp dibuat untuk menyimpan isi proyek.

    • -f|--framework: Versi .NET. Jika versi runtime adalah .NET Core 3.1, atur parameter ini ke netcoreapp3.1. Jika versi runtime adalah .NET Core 2.1, atur parameter ini ke netcoreapp2.1.

    Contoh kode berikut mengilustrasikan struktur direktori proyek:

    HelloFcApp
    ├── HelloFcApp.csproj
    ├── Program.cs
    └── obj
  2. Di direktori proyek, modifikasi pengaturan parameter dalam file sesuai situasi aktual.

    • File HelloFcApp.csproj

      File konfigurasi proyek .NET. File ini mencatat informasi seperti kerangka kerja target dan pustaka dependensi dari assembly. Tambahkan pustaka dependensi yang disediakan oleh Function Compute ke dalam file. Contoh kode berikut memberikan ilustrasi:

      <Project Sdk="Microsoft.NET.Sdk">
      
        <PropertyGroup>
          <OutputType>Exe</OutputType>
          <TargetFramework>netcoreapp3.1</TargetFramework>
        </PropertyGroup>
      
        <ItemGroup>
              <PackageReference Include="Aliyun.Serverless.Core" Version="1.0.1" />
              <PackageReference Include="Aliyun.Serverless.Core.Http" Version="1.0.3" />
        </ItemGroup>
      
      </Project>
    • File Program.cs

      Kode handler. Untuk informasi lebih lanjut, lihat Handlers. Dalam topik ini, digunakan handler acara bertipe Stream.

      using System.IO;
      using System.Threading.Tasks;
      using Aliyun.Serverless.Core;
      using Microsoft.Extensions.Logging;
      
      namespace Example
      {
          public class Hello
          {
              public async Task<Stream> StreamHandler(Stream input, IFcContext context)
              {
                  IFcLogger logger = context.Logger;
                  logger.LogInformation("Handle request: {0}", context.RequestId);
                  MemoryStream copy = new MemoryStream();
                  await input.CopyToAsync(copy);
                  copy.Seek(0, SeekOrigin.Begin);
                  return copy;
              }
      
              static void Main(string[] args){}
          }
      }

Langkah 2: Kompilasi proyek .NET

  1. Jalankan perintah berikut untuk masuk ke direktori proyek guna mengompilasi proyek dan mengeluarkan hasilnya ke direktori target:

    cd HelloFcApp && dotnet publish -c Release -o ./target
  2. Jalankan perintah berikut untuk masuk ke direktori target guna mengemas proyek:

    cd target && zip -r HelloFcApp.zip *

    Contoh kode berikut mengilustrasikan struktur paket ZIP:

    HelloFcApp.zip
    ├── Aliyun.Serverless.Core.dll
    ├── HelloFcApp.deps.json
    ├── HelloFcApp.dll
    ├── HelloFcApp.pdb
    ├── HelloFcApp.runtimeconfig.json
    └── Microsoft.Extensions.Logging.Abstractions.dll
    Penting

    Pastikan file HelloFcApp.dll dan file lainnya dikemas ke direktori root file ZIP.

Langkah 3: Terapkan kode proyek dan lakukan verifikasi

  1. Masuk ke konsol Function Compute. Di panel navigasi sisi kiri, klik Functions.

  2. Di bilah navigasi atas, pilih wilayah. Pada halaman Functions, klik Create Function.

  3. Di halaman Create Function, pilih Event Function, konfigurasikan parameter, lalu klik Create.

    Berikut adalah parameter yang harus Anda konfigurasikan di halaman Create Function. Gunakan nilai default untuk parameter lainnya.

    • Runtime: Pilih .NET Core 3.1.

    • Code Upload Method: Pilih Upload ZIP dan unggah file ZIP yang dikemas di Langkah 2.

    • Handler: Masukkan HelloFcApp::Example.Hello::StreamHandler. Untuk informasi tentang format handler, lihat Handlers.

    Setelah fungsi dibuat, Anda akan dialihkan ke tab Code pada halaman Detail Fungsi.

  4. Pada tab Code halaman Detail Fungsi, klik Test Function.

    Setelah fungsi berhasil dieksekusi, hasil berikut dikembalikan:

    {
        "key1": "value1",
        "key2": "value2",
        "key3": "value3"
    }

    Anda juga dapat mengklik tab Log Output untuk melihat informasi log.

Kompilasi dan terapkan paket kode menggunakan Serverless Devs

Before you start

Procedure

  1. Jalankan perintah berikut untuk menginisialisasi proyek:

    s init 

    Konfigurasikan Alibaba Cloud sebagai vendor cloud, templat, runtime, wilayah tempat aplikasi diterapkan, dan nama fungsi.

  2. Jalankan perintah berikut untuk masuk ke direktori proyek:

    cd start-fc3-dotnetcore

    Potongan kode berikut menunjukkan struktur direktori:

    start-fc3-dotnetcore
    ├── HelloFcApp
    │   ├── bin
    │   ├── obj
    │   ├── target
    │   ├── HelloWorldApp.csproj
    │   └── Program.cs
    ├── readme
    └── s.yaml
  3. Jalankan perintah berikut untuk menerapkan proyek:

    s deploy

    Contoh keluaran perintah:

    s.yaml: /root/start-fc3-dotnetcore/s.yaml
    Downloading[/v3/packages/fc3/zipball/0.0.24]...
    Download fc3 successfully
      Steps for [deploy] of [hello-world-app]
    ====================
    Microsoft (R) Build Engine version 16.7.3+2f374e28e for .NET
    Copyright (C) Microsoft Corporation. All rights reserved.
    
      Determining projects to restore...
      Restored /root/start-fc3-dotnetcore/HelloWorldApp/HelloWorldApp.csproj (in 154 ms).
      HelloWorldApp -> /root/start-fc3-dotnetcore/HelloWorldApp/bin/Release/netcoreapp3.1/HelloWorldApp.dll
      HelloWorldApp -> /root/start-fc3-dotnetcore/HelloWorldApp/target/
    
     [hello_world] completed (2.66s)
    
     Result for [deploy] of [hello-world-app]
    ====================
    region:         cn-hangzhou
    description:    hello world by serverless devs
    functionName:   start-dotnetcore-p6jp
    handler:        HelloWorldApp::Example.Hello::StreamHandler
    internetAccess: true
    memorySize:     128
    role:           
    runtime:        dotnetcore3.1
    timeout:        10
    
    A complete log of this run can be found in: /root/.s/logs/0327105651
  4. Jalankan perintah sudo s invoke untuk menguji fungsi.

    Contoh keluaran perintah:

      Steps for [invoke] of [hello-world-app]
    ====================
    ========= FC invoke Logs begin =========
    FunctionCompute dotnetcore3.1 runtime inited.
    FC Invoke Start RequestId: 1-6603951e-157f3f32-7fe6f248d7d0
    hello world!  
    FC Invoke End RequestId: 1-6603951e-157f3f32-7fe6f248d7d0
    
    Duration: 117.33 ms, Billed Duration: 118 ms, Memory Size: 128 MB, Max Memory Used: 13.16 MB
    ========= FC invoke Logs end =========
    
    Invoke instanceId: c-6603951e-15f440b6-2df37e4bf046
    Code Checksum: 13273801077182424526
    Qualifier: LATEST
    RequestId: 1-6603951e-157f3f32-7fe6f248d7d0
    
    Invoke Result:
    hello world!  
    ✔ [hello_world] completed (0.72s)
    
    A complete log of this run can be found in: /root/.s/logs/0327114013