Skip to content

[API Proposal]: "Multipart/form-data" serializer #104050

Open
@Mr0N

Description

@Mr0N

Background and motivation

I propose to add the "Multipart/form-data" serializer; this is just an example to make it clear what I am suggesting.

API Proposal

using System;
using System.Collections.Concurrent;
using System.Reflection;

using var client = new HttpClient();
//var form = new MultipartFormDataContent();
var obj = new MultipartContentSerialization();
var multiForm = obj.Serialization(new Info() { FirstName = "12345", LastName = "12345", Hash = "hash" });
client.PostAsync("https://google.com/test", multiForm).GetAwaiter().GetResult();

class MultipartContentSerialization
{
    public MultipartFormDataContent Serialization<T>(T obj)
    {
        var form = new MultipartFormDataContent();
        var property = obj.GetType()
           .GetProperties(BindingFlags.Public | BindingFlags.Instance);
        foreach (var item in property)
        {
            object propertyObj = item.GetValue(obj);
            var result = item.GetCustomAttribute<NamePropertyMultiformAttribute>();
            if (propertyObj is string res)
            {
                if (result is null)
                    form.Add(new StringContent(res), item.Name);
                else
                    form.Add(new StringContent(res), result.Name);
            }
            else
            {
                throw new Exception("This type is not support");
            }

        }
        return form;
    }
}
class NamePropertyMultiformAttribute(string name) : Attribute
{
    public string Name => name;
}
class Info
{
    public required string FirstName { set; get; }
    public required string LastName { set; get; }
    [NamePropertyMultiformAttribute("User Id")]
    public required string Hash { set; get; }
}

API Usage

Alternative Designs

No response

Risks

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions