Azure Functions模型绑定 [英] Azure Functions model binding

查看:74
本文介绍了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 是仅具有3个属性的POCO。

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

当我这样发布到函数时(我正在使用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)

我尝试过表单数据和x-www-form-urlencoded甚至是Postman的原始数据,每次都遇到相同的错误。我还尝试切换回 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模型绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆