Binding a string parameter to Enum type in AzureFunction
Asked Answered
B

1

6

I am trying to bind a string route parameter to Enum Type like below

public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = "ValidateKey/{keyType}/{key}")]HttpRequestMessage req, KeyType keyType, string key, TraceWriter log)

The code is giving me following exception when I hit the endpoint.

Exception binding parameter 'req' -> Invalid cast from 'System.String' to 'MyCommon.KeyType'."

The model binder is not able to bind the string parameter to Enum type. In a MVC or WebAPI application, binding to Enum works fine, but it seems like the binding is not supported in AzureFunction. Is there anyway to plugin a custom ModelBinder in AzureFunction to make it work ?

Bengaline answered 2/6, 2017 at 0:3 Comment(0)
S
5

The binding process is a bit different and we do not currently expose a mechanism to plug custom binders in.

I've opened this issue to address the specific issue, where we don't currently support binding to enums: https://github.com/Azure/azure-webjobs-sdk-script/issues/1564

In the meantime, there are a few workarounds but the most straight forward one would be to bind to a string and parse that parameter to your enum as part of your function. Not ideal, but a simple one liner:

Enum.TryParse(keyTypeValue, out KeyType keyType);
Sheply answered 2/6, 2017 at 1:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.