如何在 .NET Core 3.1 或 .NET Standard 中反序列化 x-www-form-urlencoded 编码字符串?

byt*_*dev 5 serialization .net-core x-www-form-urlencoded

如何在 .NET Core 3.1 或 .NET Standard (C#) 中反序列化 x-www-form-urlencoded 编码字符串?

我知道这个问题-答案。但是,FormDataCollection 在 .NET Core 3.1 中似乎不可用。 看这里

编辑:我正在由另一个外部系统将此编码数据传回。我不是在编写 ASP.NET Core 网站/API。

byt*_*dev 0

所以我从来没有找到这个问题的明确答案。所以我敲出了自己的粗略序列化器。发布在这里以防有人从中得到任何用处。我仍然欢迎更好的答案!:-)

using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;

public static class FormUrlEncodedSerializer
{
    public static async Task<string> SerializeAsync(object obj)
    {
        if (obj == null)
            throw new ArgumentNullException(nameof(obj));

        var keyValues = obj.GetPropertiesAsDictionary();

        var formUrlEncodedContent = new FormUrlEncodedContent(keyValues);

        return await formUrlEncodedContent.ReadAsStringAsync();
    }

    public static T Deserialize<T>(string formUrlEncodedText) where T : new()
    {
        if (string.IsNullOrEmpty(formUrlEncodedText))
            throw new ArgumentException("Form URL Encoded text was null or empty.", nameof(formUrlEncodedText));

        var pairs = formUrlEncodedText.Split('&');

        var obj = new T();

        foreach (var pair in pairs)
        {
            var nameValue = pair.Split('=');

            if (HasValue(nameValue))
            {
                obj.SetProperty(nameValue[0], nameValue[1]);
            }
        }

        return obj;
    }

    private static bool HasValue(string[] nameValue)
    {
        return nameValue.Length == 2 && nameValue[1] != string.Empty;
    }
}

public static class ObjectExtensions
{
    public static void SetProperty(this object source, string propertyName, object propertyValue)
    {
        var pi = source.GetProperty(propertyName);

        if (pi != null && pi.CanWrite)
        {
            pi.SetValue(source, propertyValue, null);
        }
    }

    public static PropertyInfo GetProperty(this object source, string propertyName)
    {
        BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.Instance;

        return source.GetType().GetProperty(propertyName, bindingFlags);
    }

    public static IDictionary<string, string> GetPropertiesAsDictionary(this object source)
    {
        var dict = new Dictionary<string, string>();

        if (source == null)
            return dict;

        var properties = source.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);

        foreach (var property in properties)
        {
            var value = property.GetValue(source);

            if (value == null)
                continue;

            dict.Add(property.Name, value.ToString());
        }

        return dict;
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑:用 GetPropertiesAsDictionary 替换 ToKeyValues。