Este tema describe el objeto de contexto disponible cuando usted escribe código en el entorno de ejecución de C# de Function Compute. Cuando Function Compute ejecuta su función, pasa un objeto de contexto al método handler. Utilice este objeto para acceder a los metadatos de invocación, las credenciales temporales y las utilidades de registro, sin necesidad de codificar valores confidenciales directamente en el código de la función.
Propiedades del contexto
Cada invocación recibe un objeto de contexto con las siguientes propiedades:
RequestId(string): identificador único de la invocación actual. Registre este valor para correlacionar solicitudes durante la resolución de errores.Function(IFunctionParameter): información básica sobre la función invocada, como el nombre, el handler, la memoria y el periodo de tiempo de espera.Credentials(ICredentials): credenciales temporales que Function Compute obtiene al asumir el rol vinculado al servicio. Estas credenciales tienen una vigencia de 36 horas e incluyen un AccessKey ID, un AccessKey secret y un token de seguridad. Úselas para acceder a otros servicios de Alibaba Cloud, como Object Storage Service (OSS), sin codificar un par de AccessKey en el código de la función. Para obtener más información, consulte Grant Function Compute permissions to access other Alibaba Cloud services.Logger(IFcLogger): registrador encapsulado por Function Compute.Service(IServiceMeta): información básica sobre el servicio al que pertenece la función.OpenTracing
Interfaz IFcContext
La interfaz IFcContext define el conjunto completo de propiedades disponibles en el objeto de contexto. Para consultar la definición completa de la interfaz, consulte 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; }
}
Uso de credenciales temporales para acceder a OSS
A continuación se muestra un ejemplo que lee las credenciales temporales del objeto de contexto y las utiliza para cargar un objeto en OSS. La función requiere que el rol vinculado al servicio tenga adjunta la directiva AliyunOSSFullAccess. El rol recomendado es AliyunFCDefaultRole.
Usar el par de AccessKey de una cuenta de Alibaba Cloud para ejecutar operaciones en Function Compute representa un riesgo alto de seguridad. En su lugar, utilice un usuario de RAM o el rol vinculado al servicio. Nunca almacene un par de AccessKey directamente en el código de la función.
Para consultar una implementación de referencia, consulte 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!");
}
}
}