如何在 HTTP 触发的 Azure 函数中绑定模型集合?

我有一个 Azure Function v2。该函数由 POST HTTP 请求触发,并获得一个帐户列表。


这是 Azure 函数:


public sealed class AccountFunction

{

    private readonly ILogger m_logger;


    public AccountFunction(ILoggerFactory loggerFactory)

    {

        m_logger = loggerFactory.CreateLogger<AccountFunction>();

    }


    [FunctionName("AccountFunction")]

    public IActionResult Run([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "v1/accounts")] List<Account> accounts)

    {

        m_logger.LogInformation("C# HTTP trigger function processed a request.");


        return new OkObjectResult(accounts);

    }

}

Account 类是一个简单的 POCO:


public class Account

{

    public string Name { get; set; }

    public string Description { get; set; }

}

我启动该函数,然后发送以下 POST 请求:


http://localhost:7071/api/v1/accounts

我在请求正文中设置了 JSON 集合:


[{ 

    "name":"A",

    "description":"covfefe"

},

 { 

    "name":"B",

    "description":"huuuggge"

}]


胡子哥哥
浏览 83回答 1
1回答

当年话下

我已经尝试过,并在本地也复制了这个问题。首先我尝试使用单个Account对象,然后将方法签名更新为 accept&nbsp;List<Account>。快速检查后,我发现了以下描述此行为的GitHub 问题。有一个关于该问题的评论,它引用了以下源文件行,其中代码明确排除了数组var&nbsp;additionalBindingData&nbsp;=&nbsp;parsed.Children<JProperty>() &nbsp;&nbsp;&nbsp;&nbsp;.Where(p&nbsp;=>&nbsp;p.Value&nbsp;!=&nbsp;null&nbsp;&&&nbsp;(p.Value.Type&nbsp;!=&nbsp;JTokenType.Array))似乎实现这一目标的唯一方法是使用解决方法。另一种方法是使用ReadAsAsync<T>扩展方法。namespace StackOverflow.AccountsQuestion{&nbsp; &nbsp; public sealed class AccountFunction&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; private readonly ILogger m_logger;&nbsp; &nbsp; &nbsp; &nbsp; public AccountFunction(ILoggerFactory loggerFactory)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; m_logger = loggerFactory.CreateLogger<AccountFunction>();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; [FunctionName("AccountFunction")]&nbsp; &nbsp; &nbsp; &nbsp; public async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "v1/accounts")] HttpRequestMessage request)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; m_logger.LogInformation("C# HTTP trigger function processed a request.");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var accounts = await request.Content.ReadAsAsync<List<Account>>();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return new OkObjectResult(accounts);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; public class Account&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; public string Name { get; set; }&nbsp; &nbsp; &nbsp; &nbsp; public string Description { get; set; }&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP