Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Attribute Routing possible in Azure Functions

I am trying to enforce a route parameter to be guid but getting below error

"Exception while executing function: GetUser -> One or more errors occurred. -> Exception binding parameter 'req' -> Invalid cast from 'System.String' to 'System.Guid'."

public static async Task<HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Admin, "get", Route = "GetUser/{userId:guid}")] HttpRequestMessage req,
            Guid userId, ILogger log)
        {
        }

The request i am making is http://localhost:7071/api/GetUser/246fb962-604d-4699-9443-fa3fa840e9eb/

Am i missing some thing? Cannot we enforce route parameter to be guid ?

like image 691
Venky Avatar asked Oct 14 '17 09:10

Venky


People also ask

How can I do routing in azure Functions?

To pass value in the function route in Azure function, we would have to modify the route parameter as “Hello/{valueName}”. Then add a parameter with the same name as the valueName in the Run method to use this value in your azure function. But adding {valueName} makes it a mandatory value to be passed.

Can an azure function have multiple routes?

Azure Functions only allow you to map a single route to a function. However the route can contain a regex. It would give you a little flexibility. You can find more information on it here.

What azure Functions can do?

Azure Functions is a serverless solution that allows you to write less code, maintain less infrastructure, and save on costs. Instead of worrying about deploying and maintaining servers, the cloud infrastructure provides all the up-to-date resources needed to keep your applications running.

What is the use of Route parameter in Httptrigger?

Using route parameters For example, if you have a route defined as "route": "products/{id}" then a table storage binding can use the value of the {id} parameter in the binding configuration. The following configuration shows how the {id} parameter is passed to the binding's rowKey .


1 Answers

Invalid cast from 'System.String' to 'System.Guid'

I can reproduce same issue when use Route constraint {userId:guid} in Azure httptrigger function on my side, you can try to open an issue to give a feedback.

Besides, if possible, you can try to call Guid.TryParse method to convert the string back to Guid value in function code, the following code is for your reference.

public static string Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = "GetUser/{userId:guid}")]HttpRequestMessage req, string userId, TraceWriter log)
{
    log.Info("C# HTTP trigger function processed a request.");

    Guid newGuid;

    var resmes = "";

    if (Guid.TryParse(userId, out newGuid))
    {
        resmes = "userid: " + newGuid;
    }
    else {
        resmes = "error";
    }

    return resmes;
}
like image 131
Fei Han Avatar answered Sep 20 '22 19:09

Fei Han