question

Kim Strasser avatar image
Kim Strasser asked

Azure Functions: How can I handle more than one function in a class?

What can I do if I have more than one function? For example, if I have two or more different functions, is it possible to write the entire code in one class or is it better to create one class for each function in Visual Studio Code?

I get error messages if I want to add a second function in the same class. Is it not possible to add a second function in this class?

namespace My.Functions
{
    public static class NewFunction
    {
        [FunctionName("NewFunction")]
        public static async Task<dynamic> MakeApiCall(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequestMessage req, ILogger log)
        {
            /* Create the function execution's context through the request */
            var context = await FunctionContext<dynamic>.Create(req);
            var args = context.FunctionArgument;

            var desireddisplayname = args["NewDisplayname"];
 
            /* Create the request object through the SDK models */
            var request = new UpdateUserTitleDisplayNameRequest();
            request.PlayFabId = context.CallerEntityProfile.Lineage.MasterPlayerAccountId;
            request.DisplayName = desireddisplayname;
            /* Use the ApiSettings and AuthenticationContext provided to the function as context for making API calls. */
            var adminApi = new PlayFabAdminInstanceAPI(context.ApiSettings, context.AuthenticationContext);
         
            /* The PlayFabServerAPI SDK methods provide means of making HTTP request to the PlayFab Main Server without any 
             * extra code needed to issue the HTTP requests. */
            return await adminApi.UpdateUserTitleDisplayNameAsync(request);
        }

       [FunctionName("ForgotPassword")]
	public static async Task<dynamic> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req, ILogger log)
	{
            log.LogInformation($"{nameof(ForgotPassword)} C# HTTP trigger function processed a request.");

        //...

            return await adminAPI.ResetPasswordAsync(new PlayFab.AdminModels.ResetPasswordRequest() {
			Password = newPassword,
			Token = tokenId
		});
    }
  }
}
The name 'ForgotPassword' does not exist in the current context [Newfunctions]

In addition, what is the difference between these two code blocks?

public static async Task<dynamic> MakeApiCall(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequestMessage req, ILogger log)

and

public static async Task<dynamic> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req, ILogger log)

Which code block should I use?

CloudScript
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

1 Answer

·
Sarah Zhang avatar image
Sarah Zhang answered

>> Is it not possible to add a second function in this class?

Yes, it’s feasible to add the second function in the class. You can add multiple methods in one class directly.
The incorrect method name causes the error. You need to use the method name “Run” in the function “name of (method name)” to fix this error. The correct code statement would be something like this.

log.LogInformation($"{nameof(Run)} C# HTTP trigger function processed a request.");

Besides, FunctionName is the attribute of this method. So if you want to get the FunctionName of a method, you can refer to the following code statement.

//Use your class name here
Type clsType = typeof(Handlers);
//Use your method name here
System.Reflection.MethodInfo mInfo = clsType.GetMethod("Run");
FunctionNameAttribute mAttr = (FunctionNameAttribute)Attribute.GetCustomAttribute(mInfo, typeof(FunctionNameAttribute));
String FunctionName = mAttr.Name;
log.LogInformation($"{FunctionName} C# HTTP trigger function processed a request.");

>> In addition, what is the difference between these two code blocks?

The first block means this function can be triggered by the Http POST method. The second block means this function can be triggered by the Http POST method and the GET method. In general, you at least need to add “post” in the method parameters when you use AzureFunctions as PlayFab CloudScript. Then you can add GET and other methods in it according to your requirements.

2 comments
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Kim Strasser avatar image Kim Strasser commented ·

Where exactly should I use Type clsType = typeof(Handlers);? I get error messages in my code.

'NewFunction.clsType': cannot declare instance members in a static class<br>The type or namespace name 'Handlers' could not be found
namespace My.Functions
{
    public static class NewFunction
    {
        Type clsType = typeof(Handlers);

[FunctionName("NewFunction")]
public static async Task<dynamic> MakeApiCall( [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequestMessage req, ILogger log)
{
// ...
}

[FunctionName("ForgotPassword")]
public static async Task<dynamic> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req, ILogger log)
{
System.Reflection.MethodInfo mInfo = clsType.GetMethod("Run");
FunctionNameAttribute mAttr = (FunctionNameAttribute)Attribute.GetCustomAttribute(mInfo, typeof(FunctionNameAttribute));
String FunctionName = mAttr.Name;


log.LogInformation($"{nameof(Run)} C# HTTP trigger function processed a request.");
//...
}
}
}
0 Likes 0 ·
Sarah Zhang avatar image Sarah Zhang Kim Strasser commented ·

As the comment said, please use your actual Class name, for your case, it should be "NewFunction".

 [FunctionName("ForgotPassword")]
        public static async Task<dynamic> Run([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req, ILogger log)
        {
            Type clsType = typeof(NewFunction);
            log.LogInformation($"{nameof(Run)} C# HTTP trigger function processed a request.");
            System.Reflection.MethodInfo mInfo = clsType.GetMethod("Run");
            FunctionNameAttribute mAttr = (FunctionNameAttribute)Attribute.GetCustomAttribute(mInfo, typeof(FunctionNameAttribute));
            String FunctionName = mAttr.Name;
            log.LogInformation($"{FunctionName} C# HTTP trigger function processed a request.");

.....
0 Likes 0 ·

Write an Answer

Hint: Notify or tag a user in this post by typing @username.

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.