4
votes

I have a compiled Azure function and I want to define a custom route using the HttpTrigger attribute.

My code looks like this:

public static async Task<HttpResponseMessage> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = "qotd/{format}")]HttpRequestMessage req, string format, TraceWriter log)
{
  var quote = GetRandomQuote();
  if (format == "json")
  {
     return req.CreateResponse(HttpStatusCode.OK, quote, "application/json");
  }
  else
  {
     var strQuote = quote.Text + Environment.NewLine + quote.Author;
     return req.CreateResponse(HttpStatusCode.OK, strQuote, "text/plain");
  }
}

When I call it like this: localhost:7071/api/qotd/json I get 404.

When I call it like this: localhost:7071/api/qotd/?format=json then the function succeeds.

If I call it like this: localhost:7071/api/qotd/ I get a rather nasty error:

"Exception while executing function: QotDFunction -> Exception binding parameter 'format' -> Binding data does not contain expected value 'format'..."

How can I define the binding in Route parameter of HttpTrigger, so that I can call my function like this:

localhost:7071/api/qotd - for a default value of parameter format

and

localhost:7071/api/qotd/json - to pass "json" as a value for format?

For Route I tried also "qotd/{format:alpha?}" but got the same results.

2

2 Answers

6
votes

It turned out that I had to explicitly rebuild the project. Rebuilding it forced VS to create a new function.json file with proper route. Without doing so, function.json still kept the old, default route.

2
votes

I test your code and do not get the same errors as you.

I create a new azure function and its default Microsoft.NET.Sdk.Functions is version of 1.0.2. And I use version 1.0.7 of Azure.Functiuons.Cli to run the function. My target framework of project is .Net Framework 4.6.1.

I use your code like below:

using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Host;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;

namespace FunctionApp1
{
    public static class Function1
    {
        [FunctionName("Function2")]
        public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = "qotd/{format:alpha?}")]HttpRequestMessage req, string format, TraceWriter log)
        {

            if (format == "json")
            {
                return req.CreateResponse(HttpStatusCode.OK, "aaa", "application/json");
            }
            else
            {
                return req.CreateResponse(HttpStatusCode.OK, "aaa", "text/plain");
            }
        }
    }
}

When I call function like http://localhost:7071/api/qotd, it passes "text" as a value for format.

enter image description here

When I call function like http://localhost:7071/api/qotd/json, it pass "json" as a value format. enter image description here