c# - HTTP 绑定(bind) Azure 函数中的自动反序列化是否考虑区域设置特定信息?

标签 c# azure azure-functions json-deserialization

当我使用 HTTP POST 和 json 正文调用我的 azure 函数时,反序列化无法按我的预期处理小数。

我在本地托管 azure 函数,并在请求正文中传输一个带有小数的 json 对象。

{
    "Receiver": {
        "Name1": "Mr. Homer Simpson",
        "AddressLine1": "742 Evergreen Terrace",
        "ZipCode": "AEED",
        "City": "Springfield",
        "CountryCode": "US"
    },
    "ReferenceNumber": "US1939383",
    "Weight": 4.2
}
    public class LabelInformation
    {
        public ParcelAddress? Receiver { get; set; }

        /// <summary>
        /// Invoice number. TODO Should be renamed.
        /// </summary>
        public string? ReferenceNumber { get; set; }

        /// <summary>
        /// Total weight of the parcel.
        /// </summary>
        public decimal? Weight { get; set; }
    }

    public class ParcelAddress
    {
        public string? Name1 { get; set; }
        public string? AddressLine1 { get; set; }
        public string? ZipCode { get; set; }
        public string? City { get; set; }
        /// <summary>
        /// Country 2 letter ISO code.
        /// </summary>
        public string? CountryCode { get; set; }
    }
        [FunctionName("GenerateLabelGLSFunctionHttpTrigger")]
        public async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "label/gls")]
            LabelInformation info)
        {
             ...
        }

将信息类型更改为字符串,然后手动反序列化该字符串,可以按预期工作。

        [FunctionName("GenerateLabelGLSFunctionHttpTrigger")]
        public async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "label/gls")]
            string info)
        {
            var labelInformation = JsonConvert.DeserializeObject<LabelInformation>(info);

            _logger.LogInformation("create the label.");
            GlsSoap.ShipmentRequestData payload = _labelService.CreateShipmentRequestData(labelInformation);

我收到的错误是

[09.10.2019 10:28:38] Executed 'GenerateLabelGLSFunctionHttpTrigger' (Failed, Id=90330456-1ac2-43f3-9285-ab2284b6c31f)
[09.10.2019 10:28:38] System.Private.CoreLib: Exception while executing function: GenerateLabelGLSFunctionHttpTrigger. Microsoft.Azure.WebJobs.Host: Exception binding parameter 'info'. System.Private.CoreLib: Input string was not in a correct format.
[09.10.2019 10:28:38] fail: Host.Results[0]
Microsoft.Azure.WebJobs.Host.FunctionInvocationException: Exception while executing function: GenerateLabelGLSFunctionHttpTrigger ---> System.InvalidOperationException: Exception binding parameter 'info' ---> System.FormatException: Input string was not in a correct format.
   at System.Number.ParseSingle(ReadOnlySpan`1 value, NumberStyles options, NumberFormatInfo numfmt)
   at System.String.System.IConvertible.ToSingle(IFormatProvider provider)
   at System.Convert.ChangeType(Object value, Type conversionType, IFormatProvider provider)
   at Microsoft.Azure.WebJobs.Extensions.Http.HttpTriggerAttributeBindingProvider.HttpTriggerBinding.ConvertValueIfNecessary(Object value, Type targetType) in C:\azure-webjobs-sdk-extensions\src\WebJobs.Extensions.Http\HttpTriggerAttributeBindingProvider.cs:line 415
...

我希望自动反序列化不使用区域设置信息(在我的操作系统上它是德语 - 如果我更改为英语,一切都会按预期工作)来反序列化小数。

或者请解释一下,为什么这应该很好,因为函数可以托管在不同的区域设置上,并且该函数的调用者需要知道函数部署在哪里才能考虑到正确的小数分隔符。

最佳答案

我在您的类定义中看到很多声明问题:

这是我的代码,运行良好:

using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;

namespace FunctionAppPostComplexObject
{
    public static class Function1
    {
        [FunctionName("Function1")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] LabelInformation info,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            LabelInformation labelInformation = info;

            //_logger.LogInformation("create the label.");
            string name = "";// req.Query["name"];

            //string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
          //  dynamic data = JsonConvert.DeserializeObject(requestBody);
          //  name = name ?? data?.name;

            return name != null
                ? (ActionResult)new OkObjectResult($"Hello, {name}")
                : new BadRequestObjectResult("Please pass a name on the query string or in the request body");
        }

        public class LabelInformation
        {
            public ParcelAddress Receiver { get; set; }

            /// <summary>
            /// Invoice number. TODO Should be renamed.
            /// </summary>
            public string ReferenceNumber { get; set; }

            /// <summary>
            /// Total weight of the parcel.
            /// </summary>
            public decimal? Weight { get; set; }
        }

        public class ParcelAddress
        {
            public string Name1 { get; set; }
            public string AddressLine1 { get; set; }
            public string ZipCode { get; set; }
            public string City { get; set; }
            /// <summary>
            /// Country 2 letter ISO code.
            /// </summary>
            public string CountryCode { get; set; }
        }
    }
}

这是信息的值:

enter image description here

检查一下,看看是否有帮助。

关于c# - HTTP 绑定(bind) Azure 函数中的自动反序列化是否考虑区域设置特定信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58303041/

相关文章:

Azure CLI 使用AllowImplicit 创建 AD 应用程序

azure - mac - az 命令未找到 azure

azure - 通过 Azure Runbook 部署 ARM 模板

c# - 在我的预编译 C# Azure Function 中引用 dll

node.js - 主动机器人中重复的英雄卡响应

c# - Newtonsoft.JSON Mono Float反序列化异常

c# - 存储更新、插入或删除语句影响了意外数量的行 (0)

c# - 将数据集 (.net) 中的列加载到字符串 [] 中的最佳方法是什么?

c# - LINQPad索引超出范围异常

c# - Azure Function 与源一起发布