Make the MongoDB docs better! We value your opinion. Share your feedback for a chance to win $100.
Click here >
Docs Menu
Docs Home
/ /
Servicios de aplicaciones

Call a Function - .NET SDK

Los ejemplos de esta sección demuestran cómo llamar a un Función de reino nombrada sum que toma dos argumentos, los suma y devuelve el resultado:

// sum: adds two numbers
exports = function(a, b) {
return a + b;
};

Nota

Authenticate First

Llamas a Functions en un objeto Usuario, así que antes de llamar a cualquier función, debes autenticar a un usuario.

Importante

Make sure to sanitize client data to protect against code injection when using Functions.

Para ejecutar una función desde el SDK .NET, utilice el método Functions.CallAsync() en el User objeto, pasando el nombre de la función como primer parámetro y los argumentos como los parámetros restantes:

var bsonValue = await
user.Functions.CallAsync("sum", 2, 40);
// The result must now be cast to Int32:
var sum = bsonValue.ToInt32();
// Or use the generic overloads to avoid casting the BsonValue:
sum = await
user.Functions.CallAsync<int>("sum", 2, 40);

Nota

The CallAsync() method returns a single BsonValue object, which you can deserialize after calling the function or by using the the generic overload. Both of these approaches to deserialization are shown in the code above.

A BsonValue object can hold a single primitive value (as shown in the example above), or hold a complete BSON document. If you have a class that maps to the returned object, you can deserialize to that class by using the generic overload. For example, the following code calls a function that returns an object from a collection of "RealmTasks". Since we know the shape of the returned object, we we can deserialize the BsonValue to a class that we have created, and then we have access to the properties and methods on that object:

var item = await user.Functions.CallAsync<MyClass>
("getItem", "5f7f7638024a99f41a3c8de4");
var name = item.Name;

Volver

Connect to an App Services App

En esta página