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 ?
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);