Refit: Allow sending custom classes in multipart

Created on 16 Jul 2015  路  8Comments  路  Source: reactiveui/refit

Currently you can only send String, Stream, FileInfo, and Byte array in a multipart request.
it would be useful to allow other custom classes to be sent by converting them to JSON

i think that all it takes is to add the following code at the end of the RequestBuilderImplementation.addMultipartItem(...) method

try 
{
    var stringContent = new StringContent(JsonConvert.SerializeObject(itemValue, settings.JsonSerializerSettings), Encoding.UTF8, "application/json");
    multiPartContent.Add(stringContent, itemName);
    return;
} 
catch (Exception ex)
{
    throw new ArgumentException(string.Format("Unexpected parameter type in a Multipart request. Parameter {0} is of type {1}, whereas allowed types are String, Stream, FileInfo, and Byte array or a type that can be converted to json", itemName, itemValue.GetType().Name), "itemValue",ex);

}

what do you think? i can create a pull request if it sounds good

enhancement outdated

All 8 comments

Totally agree.
+1

It definitely useful!

Looks like a good solution

Fixed in #426. Please file a new issue if there's still things missing.

Hi guys thanks for making this available!
I've got stuck with this, just created a class with a stream and a string:

public class Upload
{
    public Stream media { get; set; }
    public Configuration configuration { get; set; }
}

Then using it on the interface

[Multipart]
[Post("/media")]
Task<Media> UploadMediaWithConfiguration([Header("Authorization")] string authorization,
            Upload upload);

But I get the error:

{"Unexpected parameter type in a Multipart request. Parameter upload is of type Upload, whereas allowed types are String, Stream, FileInfo, Byte array and anything that's JSON serializable\r\nParameter name: itemValue"}

@ianrathbone that's not going to work like that since each parameter needs to be its own part in the overall content. You'd need to split those into separate parameters. The POCO case turns into a JSON string payload.

One other suggestion -- you can use the AuthorizationTokenGetter func on the Refit settings to plug in a token cache/value, etc. so you don't need to pass it on every api call. Just add [Headers("Authorization: Bearer")] as an attribute to the methods where you want it, and it'll call your func to get the value.

@onovotny great I'll get working on that. And thank you for the tip on AuthorizationTokenGetter - I had no idea about that one!!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ML13 picture ML13  路  4Comments

jstafford5380 picture jstafford5380  路  4Comments

mary-perret-1986 picture mary-perret-1986  路  5Comments

fonix232 picture fonix232  路  4Comments

AnjaliSahu51 picture AnjaliSahu51  路  4Comments