c# - Azure Function 不反序列化对象

标签 c# json azure visual-studio-2017 azure-functions

在最新版本的 Azure Functions 中,我无法获取用于反序列化对象的函数。

版本:

Azure Functions 核心工具:1.0.0-beta.100

函数运行时版本:1.0.11015.0

Visual Studio:15.3.0 预览版 4.0

示例(不起作用):

[FunctionName("Login")]
public static async Task<HttpResponseMessage> Login([HttpTrigger(AuthorizationLevel.Function, "post", Route = null)]HttpRequestMessage req, ILogger log, AuthenticatingUser user)
{
    return await Task.Run(() =>
    {
        return req.CreateResponse(HttpStatusCode.OK, user.Username);
    });
}

当尝试使用 Postman 发送此函数时,我总是收到以下错误:

Exception while executing function: Functions.Login. Microsoft.Azure.WebJobs.Host: Exception binding parameter 'user'. Microsoft.Azure.WebJobs.Host: No value was provided for parameter 'user'.

我尝试过使用表单数据、x-www-form-urlencoded 和 raw 进行发布(选择了 JSON - 我期望的工作)。所有最终都会出现相同的错误。

当我从函数中取出用户时,我可以通过以下方式访问传入的 JSON:

var content = req.Content;
string jsonContent = content.ReadAsStringAsync().Result;

在以前版本的 Azure Functions 中(值得注意的是,不是使用 Visual Studio 扩展构建的,涉及 JSON 文件等),这按预期工作。

我发布了以下内容的各种版本:

{
    "Username": "myUserName",
    "Password": "MyPassword123"
}

用户模型:

public class AuthenticatingUser
{
    public string Username { get; set; }
    public string Password { get; set; }
}

最佳答案

您应该使用 HttpTrigger 属性标记 user 参数:

public static async Task<HttpResponseMessage> Login(
    HttpRequestMessage req, 
    [HttpTrigger(AuthorizationLevel.Function, "post")] AuthenticatingUser user)

req 仍将被填充,且不带任何属性。

确保请求的 Content-Type header 设置为 application/json。鉴于此,该函数将使用请求正文中的 JSON。

关于c# - Azure Function 不反序列化对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45130757/

相关文章:

Azure Blob 存储,如何使用访问 token 访问所有文件内容

c# - 如何调试 WCF 程序

c# - 使用 PowerShell 查找最接近的 System.Color 实例

c# - DropDownList 获得空白选择

javascript - 将 "[ with [ and ]"替换为 ] json

javascript - Jquery中如何将DropdownList转换为Json

c# - 等待 IObservable 获取所有元素错误

javascript - 在 django 模板 [python] 中使用 json.dump 或 pprint 逐行创建一个表

azure - 什么是有效的 IP 范围?

azure - Xml 到 Json 液体模板停止在 Azure 逻辑应用上工作