Is Attribute Routing possible in Azure Functions

2019-04-09 21:36发布

问题:

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 ?

回答1:

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;
}