Azure Functions model binding(Azure Functions 模型绑定)
问题描述
我创建了一个 Azure 函数并在本地运行它:
I've created an Azure Function and I'm running it locally:
[FunctionName("HttpTriggerCSharpSet")]
public static async Task<HttpResponseMessage> Set([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] MyDocument req, TraceWriter log)
{
   // ...
}
请注意,MyDocument 是第一个参数,而不是 HttpRequestMessage.我在文档中读到这种方法应该可以工作,并且它似乎与 ASP.NET 模型绑定非常相似(无论如何,在我看来).MyDocument 是一个 POCO,只有 3 个属性.
Notice that MyDocument is the first parameter instead of HttpRequestMessage. I've read in the documentation that this approach should work, and it seems very similar to ASP.NET model binding (in my mind, anyway). MyDocument is a POCO with just 3 properties.
public class MyDocument
{
    public string Name { get; set; }
    public int ShoeSize { get; set; }
    public decimal Balance { get; set; }
}
当我像这样 POST 到函数时(我正在使用 Postman):
When I POST to the function like so (I'm using Postman):
我收到一条错误消息:[8/8/2017 2:21:07 PM] 执行函数时出现异常:Functions.HttpTriggerCSharpSet.Microsoft.Azure.WebJobs.Host:异常绑定参数req".System.Net.Http.Formatting:没有 MediaTypeFormatter 可用于从内容中读取MyDocument"类型的对象(您也可以在上面的 Postman 屏幕截图中看到)
I get an error message: [8/8/2017 2:21:07 PM] Exception while executing function: Functions.HttpTriggerCSharpSet. Microsoft.Azure.WebJobs.Host: Exception binding parameter 'req'. System.Net.Http.Formatting: No MediaTypeFormatter is available to read an object of type 'MyDocument' from content (which you can also see in the screenshot of Postman above)
我已经尝试过来自 Postman 的 form-data 和 x-www-form-urlencoded,甚至是 raw,每次都出现同样的错误.我也尝试切换回 HttpRequestMessage 并使用 req.Content.ReadAsAsync<MyDocument>,我得到了类似的错误.我是在错误地构建我的 POST,还是我错误地编写了我的 Azure 函数.无论哪种情况,正确的方法是什么?
I've tried form-data and x-www-form-urlencoded and even raw from Postman, same error every time. I've also tried switching back to HttpRequestMessage and using req.Content.ReadAsAsync<MyDocument>, and I get a similar error. Am I constructing my POST incorrectly, or am I writing my Azure Function incorrectly. In either case, what's the correct way?
推荐答案
一定要指定标题:
Content-Type: application/json
那么以下主体应该适用于您的代码:
then the following body should work for your code:
{
    "Name": "myUserName",
    "Balance": 123.0,
    "ShoeSize": 30
}
这篇关于Azure Functions 模型绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Azure Functions 模型绑定
 
				
         
 
            
        - 输入按键事件处理程序 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
 
						 
						 
						 
						 
						 
				 
				 
				 
				