首页 > 解决方案 > 是否考虑区域设置特定信息在 HTTP 绑定 Azure 函数中的自动反序列化?

问题描述

当我使用 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
...

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

或者请解释一下,为什么这应该很好,因为函数可以托管在不同的语言环境中,并且该函数的调用者需要知道函数的部署位置以考虑正确的十进制分隔符。

标签: c#azureazure-functionsjson-deserialization

解决方案


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

这是我完美运行的代码:

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

这是信息的价值:

在此处输入图像描述

检查这个,看看它是否有帮助。


推荐阅读