Bu konu, Function Compute C# çalışma zamanı ortamında kod yazarken kullanabileceğiniz bağlam nesnesini açıklar. Function Compute işlevinizi çalıştırdığında, işleyici yöntemine bir bağlam nesnesi iletir. İşlev kodunuzda hassas değerleri sabit olarak belirtmeden çağırma meta verilerine, geçici kimlik bilgilerine ve günlük kaydı yardımcı programlarına erişmek için bu nesneyi kullanın.
Bağlam özellikleri
Her çağırma işlemi aşağıdaki özelliklere sahip bir bağlam nesnesi alır:
RequestId(string) — Geçerli çağırmanın benzersiz kimliği. Hataları giderirken istekleri ilişkilendirmek amacıyla bu değeri günlüğe kaydedin.Function(IFunctionParameter) — Çağrılan işlevin adı, işleyici, bellek ve zaman aşımı süresi dahil olmak üzere temel bilgileri içerir.Credentials(ICredentials) — Function Compute tarafından hizmet bağlantılı rolünüz üstlenilerek alınan geçici kimlik bilgileri. Bu kimlik bilgileri 36 saat geçerlidir ve bir AccessKey ID, AccessKey secret ile güvenlik belirtecini içerir. İşlev kodunuzda bir AccessKey çiftini sabit olarak belirtmeden Object Storage Service (OSS) gibi diğer Alibaba Cloud hizmetlerine erişmek için bu kimlik bilgilerini kullanın. Daha fazla bilgi için bkz. Grant Function Compute permissions to access other Alibaba Cloud services.Logger(IFcLogger) — Function Compute tarafından kapsüllenmiş günlük kaydedici.Service(IServiceMeta) — İşlevin ait olduğu hizmetin temel bilgileri.OpenTracing
IFcContext arabirimi
IFcContext arabirimi, bağlam nesnesinde bulunan tüm özellik kümesini tanımlar. Arabirim tanımının tamamı için bkz. IFcContext.
public interface IFcContext
{
/// <summary>
/// The AliFc request ID associated with the request.
/// This is the same ID returned to the client that called invoke().
/// This ID is reused for retries on the same request.
/// </summary>
string RequestId { get; }
/// <summary>
/// Gets the function parameter interface.
/// </summary>
/// <value>The function parameter interface.</value>
IFunctionParameter FunctionParam {get;}
/// <summary>
/// AliFc logger associated with the Context object.
/// </summary>
IFcLogger Logger { get; }
/// <summary>
/// Gets the credentials interface.
/// </summary>
/// <value>The credentials interface.</value>
ICredentials Credentials {get;}
/// <summary>
/// Gets the account identifier.
/// </summary>
/// <value>The account identifier.</value>
string AccountId { get; }
/// <summary>
/// Gets the region.
/// </summary>
/// <value>The region.</value>
string Region { get; }
/// <summary>
/// Gets the service meta.
/// </summary>
/// <value>The service meta.</value>
IServiceMeta ServiceMeta { get; }
}
OSS'e erişmek için geçici kimlik bilgilerini kullanma
Aşağıdaki örnekte, bağlam nesnesinden geçici kimlik bilgileri okunur ve bunlar kullanılarak OSS'e bir nesne yüklenir. İşlevin, hizmet bağlantılı rolüne AliyunOSSFullAccess ilkesinin eklenmiş olmasını gerektirir. Önerilen rol AliyunFCDefaultRole rolüdür.
Bir Alibaba Cloud hesabının AccessKey çiftini kullanarak Function Compute içinde işlem yapmak yüksek riskli bir uygulamadır. Bunun yerine bir RAM kullanıcısı veya hizmet bağlantılı rol kullanın. AccessKey çiftini asla doğrudan işlev kodunuzda saklamayın.
Referans bir uygulama için bkz. dotnet3-oss.
using System;
using System.IO;
using Aliyun.OSS;
using Aliyun.Serverless.Core;
using Microsoft.Extensions.Logging;
namespace Example
{
public class OssExample
{
public Stream HandleRequest(Stream stream, IFcContext context)
{
context.Logger.LogInformation("Handle request: {0}", context.RequestId);
// The bucket name. Create the bucket before running this function.
string bucketName = "my-****";
// The full path of the object to upload.
string objectName = "exampledir/exampleobject.txt";
// Use the internal endpoint of the region where the bucket resides.
// This example uses the internal endpoint for the China (Hangzhou) region.
string endpoint = "https://oss-cn-hangzhou-internal.aliyuncs.com";
// Get temporary credentials from the context object.
// These credentials are issued by the service-linked role configured for the function.
ICredentials creds = context.Credentials;
// Create an OssClient instance using the temporary credentials.
OssClient ossClient =
new OssClient(endpoint,
creds.AccessKeyId,
creds.AccessKeySecret,
creds.SecurityToken);
// Upload the input stream as an object.
ossClient.PutObject(bucketName, objectName, stream);
// Retrieve the uploaded object and return its content.
OssObject obj = ossClient.GetObject(bucketName, objectName);
context.Logger.LogInformation("Put object to OSS success: {0}", obj.ToString());
return obj.Content;
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}