问题描述
我创建了一个 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 模型绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!