Using the YcFunction interface to set a handler function in C#
You can set a handler function in C# by implementing the YcFunction interface. To do this, add an SDK to the dependencies.
Warning
You should specify both values for YcFunction
type parameters, the first one being the input argument type and the second one the type of the return value. The handle
method also has invocation context as its second argument.
Example of a valid handler:
public class Handler : YcFunction<int, String> {
public String FunctionHandler(int i, Context c) {
return String.valueOf(i);
}
}
Examples of invalid handlers:
// YcFunction has only one parameter type specified
// Handler should not have any type parameters (see the [handler requirements](index.md))
public class Handler<T> : YcFunction<T, int> {
public int FunctionHandler(T i, Context c) {
return 2;
}
}
// YcFunction doesn't have both parameter types specified
public class Handler : YcFunction {
public Object FunctionHandler(Object i, Context c) {
return i;
}
}
You can use any classes as input and return types.
Note
Fields of these classes may have any access modifiers. If a field is non-public, it requires a public getter
method. Otherwise, the field won't be included in the response.
Example
Function information output
The following function:
- Receives a number as an input.
- Outputs the function data obtained from the invocation context to the execution log.
- Returns data on whether the received number is even.
Warning
To invoke the function, use the YC CLI or an HTTP request with the integration=raw
parameter.
The Handler.cs file:
using Yandex.Cloud.Functions;
public class Handler : YcFunction<int, bool> {
public bool FunctionHandler(int number, Context c) {
Console.WriteLine($"Function name: {c.FunctionId}");
Console.WriteLine($"Function version: {c.FunctionVersion}");
Console.WriteLine($"Service account token: {c.TokenJson}");
return number % 2 == 0;
}
}
Example of input data:
41
The log will contain the following:
Function name: <your function name>
Function version: <your function version ID>
Service account token: <token for your service account>
Returned string:
false