mardi 25 septembre 2018

Post embedded objects as multipart form data

I have a method that sends a model to a server as multipart form data but I can't think how to post embedded objects, for example:

public class Model1
{
   public string Field {get;set;}
}

public class Model2
{
   public Model1 Model {get;set;}
}

I create multipart data like this:

var boundary = CreateFormDataBoundary();
                var postData = model.GetType()
                .GetProperties(BindingFlags.Instance | BindingFlags.Public)
                .ToDictionary(prop => prop.Name, prop => prop.GetValue(model, null));

            var request = (HttpWebRequest)WebRequest.Create(url + path);
            request.Method = "POST";
            request.KeepAlive = true;
            request.ContentType = "multipart/form-data; boundary=" + boundary;

            var requestStream = request.GetRequestStream();

            foreach (var item in postData)
            {
                if (item.Value != null)
                {
                    //if list of strings
                    if (item.Value is IEnumerable<string> fields)
                    {
                        if (fields != null)
                            foreach (var field in fields)
                                WriteMultipartFormData(new KeyValuePair<string, string>(item.Key, field), requestStream, boundary);
                    }
                    else
                    {
                        WriteMultipartFormData(new KeyValuePair<string, string>(item.Key, item.Value?.ToString()), requestStream, boundary);
                    }
                }
            }

            var endBytes = Encoding.UTF8.GetBytes("--" + boundary + "--");

            requestStream.Write(endBytes, 0, endBytes.Length);
            requestStream.Close();

So do I need to make some recursive method that watches at either field type is object or not and write data depending on it? If so, I don't understand how to find out what type it is. Just write if (item.Value is object)?




Aucun commentaire:

Enregistrer un commentaire