【问题标题】:Custom routing in Azure functions using HttpTrigger attribute使用 HttpTrigger 属性在 Azure 函数中自定义路由
【发布时间】:2018-06-26 13:43:01
【问题描述】:

我有一个已编译的 Azure 函数,我想使用 HttpTrigger 属性定义一个自定义路由。

我的代码如下所示:

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

当我这样称呼它时: localhost:7071/api/qotd/json 我得到 404。

当我这样称呼它时: localhost:7071/api/qotd/?format=json 那么函数就成功了。

如果我这样称呼它: 本地主机:7071/api/qotd/ 我得到一个相当讨厌的错误:

"执行函数时出现异常:QotDFunction -> 异常绑定 参数“格式”-> 绑定数据不包含预期值 '格式'...”

如何在 HttpTrigger 的 Route 参数中定义绑定,以便我可以这样调用我的函数:

localhost:7071/api/qotd - 参数格式的默认值

localhost:7071/api/qotd/json - 将“json”作为格式值传递?

对于路线,我也尝试了“qotd/{format:alpha?}”,但得到了相同的结果。

【问题讨论】:

    标签: c# function azure


    【解决方案1】:

    我测试了你的代码,没有遇到和你一样的错误。

    我创建了一个新的 azure 函数,它的默认 Microsoft.NET.Sdk.Functions 版本是 1.0.2。我使用版本 1.0.7 的 Azure.Funtiuons.Cli 来运行该函数。我的项目目标框架是.Net Framework 4.6.1。

    我使用你的代码如下:

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

    当我调用像http://localhost:7071/api/qotd 这样的函数时,它会将“文本”作为格式值传递。

    当我调用像http://localhost:7071/api/qotd/json 这样的函数时,它会将“json”作为值格式传递。

    【讨论】:

    • "if" 语句在单个方法中选择请求方法或标头是猴子代码。如果 MS 不允许做普通的 api,那么它的设计 bug 和有设计 bug 的技术在修复之前不应该使用。
    【解决方案2】:

    事实证明,我必须明确地重新构建项目。重建它迫使 VS 创建一个具有正确路径的新 function.json 文件。如果不这样做,function.json 仍然保留旧的默认路由。

    【讨论】:

      猜你喜欢
      • 2020-12-13
      • 2013-06-11
      • 1970-01-01
      • 1970-01-01
      • 2015-04-26
      • 1970-01-01
      • 2015-05-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多