Handler

Updated at:

Use a C# handler to respond to received events and run the corresponding business logic. This topic describes the concepts, structural features, and examples of C# handlers.

Note

If you want to use HTTP triggers or custom domain names to access functions, obtain request struct before you define HTTP responses. For more information, see Use an HTTP trigger to invoke a function.

What is a handler?

FC function handlers are the methods in the function code that process requests. When your FC function is invoked, Function Compute runs the handler method that you provide to process the request.

You can use Function Compute console to configure the handler for a function when you create or update the function. For instructions, see Create an event-triggered function.

For FC functions written in C#, the handler is in the following format: Assembly name::Namespace.Class name::Method name (Assembly::Namespace.ClassName::MethodName).

Parameter

Description

Assembly

The name of the assembly that you create.

Namespace

The namespace name.

ClassName

The class name.

MethodName

The method name.

Assume that the assembly name is HelloFcApp. In this case, the handler is configured as HelloFcApp::Example.HelloFC::StreamHandler. The following example shows a simple program:

using System.IO;

namespace Example
{
    public class HelloFC
  {
      public async Task<Stream> StreamHandler(Stream input)
    {
        //function logic
    }
  }
}

Configurations of handlers must conform to the configuration specifications of Function Compute. The configuration specifications vary based on the handler type.

Handler interface

When you create a C# function, you must specify a handler method that runs when the function is invoked. This handler method can be a static method or an instance method. To access the IFcContext object in the handler method, specify the second parameter of the method as an IFcContext object. Event functions support the following handler method definitions:

ReturnType HandlerName(InputType input, IFcContext context);  //Includes IFcContext.
ReturnType HandlerName(InputType input); // Does not include IFcContext.
Async Task<ReturnType> HandlerName(InputType input, IFcContext context);
Async Task<ReturnType> HandlerName(InputType input);

Function Compute supports Async in functions written in C#. In this case, the function execution waits for the asynchronous method call to complete. The following list describes ReturnType, InputType, and IFcContext:

  • ReturnType: The returned object can be void, a System.IO.Stream object, or any object that can be JSON serialized and deserialized. If the returned object is a Stream, the Stream content is returned directly in the response body. Otherwise, the returned object is JSON serialized and returned in the response body.

  • InputType: The input parameter can be System.IO.Stream or any object that can be JSON serialized and deserialized.

  • IFcContext: The Context object of the function. For more information, see Context.

Event handler types

To write functions in C# in Function Compute, you must add the Aliyun.Serverless.Core dependency package. You can add this package to the .csproj file in the following way:

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

Aliyun.Serverless.Core package defines two parameter types for event handlers.

  • Stream Handler

    Receives the input event as a stream and returns the execution result. When the function is invoked, you must read the input from the input stream. After processing is complete, write the function execution result to the output stream to return it.

  • POCO Handler

    With the POCO (Plain old CLR objects) approach, you can customize the input and output types. However, the input and output types must be POCO types.

Stream Handler

The following example shows the simplest Stream Handler:

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){}
    }
}

The following list describes the example:

  • Namespace and class

    The namespace is Example, the class name is Hello, and the method name is StreamHandler. Assume that the assembly name is HelloFcApp. In this case, the handler is configured as HelloFcApp::Example.Hello::StreamHandler.

  • Parameter Stream input

    The input of the handler. In this example, the input type is Stream.

  • Parameter IFcContext context (optional)

    The context object, which contains information about the function and the request.

  • Return value Task<Stream>

    The return value is of the Stream type.

POCO Handler

The following example shows the simplest POCO Handler:

using Aliyun.Serverless.Core;
using Microsoft.Extensions.Logging;

namespace Example
{
    public class Hello
    {
        public class Product
        {
            public string Id { get; set; }
            public string Description { get; set; }
        }

        // optional serializer class, if it’s not specified, the default serializer (based on JSON.Net) will be used.
        // [FcSerializer(typeof(MySerialization))]
        public Product PocoHandler(Product product, IFcContext context)
        {
            string Id = product.Id;
            string Description = product.Description;
            context.Logger.LogInformation("Id {0}, Description {1}", Id, Description);
            return product;
        }

        static void Main(string[] args){}
    }
}

In addition to Stream as the input and output parameter, POCO (Plain old CLR objects) objects can also be used as the input and output. If the POCO does not specify a particular JSON serialization object, Function Compute uses JSON.Net by default to perform JSON serialization and deserialization of the object. The details are as follows:

  • Namespace and class

    The namespace is Example, the class name is Hello, and the method name is PocoHandler. Assume that the assembly name is HelloFcApp. In this case, the handler is configured as HelloFcApp::Example.Hello::PocoHandler.

  • Parameter Product product

    The input of the handler. In this example, the input type is Product Class. If the POCO does not specify a particular JSON serialization object, Function Compute uses JSON.Net by default to perform JSON deserialization of the object.

  • Parameter IFcContext context (optional)

    The context object, which contains information about the function and the request.

  • Return value Product

    The return value is of the POCO Product type. If the POCO does not specify a particular JSON serialization object, Function Compute uses JSON.Net by default to perform JSON serialization of the object.

Custom Serializer

For POCO Handlers, Function Compute provides a default serialization interface based on JSON .NET. If the default serialization interface does not meet your requirements, you can use the Aliyun.Serverless.Core interface IFcSerializer to implement a custom serialization interface.

public interface IFcSerializer
{
    T Deserialize<T>(Stream requestStream);
    void Serialize<T>(T response, Stream responseStream);
}      

Invoke a function by using an HTTP trigger

Sample code

using System;
using System.Collections.Generic;
using System.Text;
using System.Text.Json;
using Aliyun.Serverless.Core;
using Microsoft.Extensions.Logging;

namespace Example
{
    public class Hello
    {
        public class HTTPTriggerEvent
        {
            public string Version { get; set; }
            public string RawPath { get; set; }
            public string Body { get; set; }
            public bool IsBase64Encoded { get; set; }
            public RequestContext RequestContext { get; set; }
            public Dictionary<string, string> Headers { get; set; }
            public Dictionary<string, string> QueryParameters { get; set; }

            public override string ToString()
            {
                return JsonSerializer.Serialize(this);
            }
        }

        public class RequestContext
        {
            public string AccountId { get; set; }
            public string DomainName { get; set; }
            public string DomainPrefix { get; set; }
            public string RequestId { get; set; }
            public string Time { get; set; }
            public string TimeEpoch { get; set; }
            public Dictionary<string, string> Http { get; set; }
        }

        public class HTTPTriggerResponse
        {
            public int StatusCode { get; set; }
            public Dictionary<string, string> Headers { get; set; }
            public bool IsBase64Encoded { get; set; }
            public string Body { get; set; }
        }

        public HTTPTriggerResponse PocoHandler(HTTPTriggerEvent input, IFcContext context)
        {
            context.Logger.LogInformation("receive event: {0}", input.ToString());
            string requestBody = input.Body;
            if (input.IsBase64Encoded)
            {
                byte[] decodedBytes = Convert.FromBase64String(input.Body);
                requestBody = Encoding.UTF8.GetString(decodedBytes);
            }
            return new HTTPTriggerResponse
            {
                StatusCode = 200,
                IsBase64Encoded = false,
                Body = requestBody
                };
        }
        static void Main(string[] args){}
    }
}

Prerequisites

A function whose runtime environment is C#, created by using the preceding example. For instructions, see Create an event-triggered function and Configure an HTTP trigger.

Procedure

  1. Log on to the Function Compute console. In the left-side navigation pane, click Functions.

  2. In the top navigation bar, select a region. On the Functions page, click the function that you want to manage.

  3. On the function details page, click the Trigger tab. On the Trigger page, get the public network access address of the HTTP trigger.

  4. Run the following command in Curl to invoke the function:

    curl -i "https://test-python-ipgrwr****.cn-shanghai.fcapp.run" -d 'Hello fc3.0'

    In the preceding command, https://test-python-ipgrwr****.cn-shanghai.fcapp.run is the public network access address of the HTTP trigger that you obtained.

    Important
    • If the HTTP trigger's Authentication Method is No Authentication, you can invoke the function directly by using Postman or Curl. For instructions, see Invoke the function in this topic.

    • If the HTTP trigger's Authentication Method is Signature Authentication, JWT authentication, or Bearer authentication, use the signature method, JWT authentication, or Bearer authentication to invoke the function. For instructions, see Authentication and authorization.

    The following response is returned:

    HTTP/1.1 200 OK
    Content-Disposition: attachment
    Content-Length: 12
    Content-Type: application/json
    X-Fc-Request-Id: 1-64f7449a-127fbe39cd7681596e33ebad
    Date: Tue, 05 Sep 2023 15:09:14 GMT
    
    Hello fc3.0

Error analysis

This sample code supports invocation by using an HTTP trigger or a custom domain name. If you invoke the function by using an API but the configured test parameters do not conform to the HTTP trigger request format specification, an error occurs.

For example, invoke the function in the console with the request parameter set to "Hello, FC!", and click Test Function. You receive the following response:

{
    "errorMessage": "Unexpected character encountered while parsing value: H. Path '', line 0, position 0.",
    "errorType": "Newtonsoft.Json.JsonReaderException",
    "stackTrace": [
        "   at Newtonsoft.Json.JsonTextReader.ParseValue()",
        "   at Newtonsoft.Json.JsonReader.ReadAndMoveToContent()",
        "   at Newtonsoft.Json.JsonReader.ReadForType(JsonContract contract, Boolean hasConverter)",
        "   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)",
        "   at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)",
        "   at Newtonsoft.Json.JsonSerializer.Deserialize(JsonReader reader, Type objectType)",
        "   at Newtonsoft.Json.JsonSerializer.Deserialize[T](JsonReader reader)",
        "   at Aliyun.Serverless.Core.JsonSerializer.Deserialize[T](Stream requestStream) in /dotnetcore/Libraries/src/Aliyun.Serverless.Core.Impl/JsonSerializer.cs:line 95"
    ]
}

Sample programs

The official Function Compute repository contains sample applications that use various handler types and interfaces. Each sample application includes a method for easy compilation and deployment.