How to read Multipart MIME data from HttpResponseMessage in .NET Standard

Deep Blue Day
2 min readMar 7, 2019

--

35mm Expired Film — Ricoh GR

I am working on a .NET Standard library to act as a wrapper for a third party REST API.

Why .NET Standard? Because I want this library to be reusable across all .NET platforms (.NET Core, .NET Framework, Xamarin, etc), which means we can use the exact same code either on Mobile devices, Windows services, AWS Lambda functions, etc. More info on .NET Standard here.

Circling back to the problem at hand. There is one particular API call that is used to bulk retrieve multiple documents in one request. This request returns any number of documents, as individual bodies in a MIME multipart response. Each enclosed body contains one requested document.

The response of this API call looks something like the below:

--ba2576699d9e3222340bd07aa7d345d37c40210046d1a78e592efd6ef9c6
Content-Type: application/json
{\"Date\":\"2019-03-07T15:39:03\",\"CUID\":\"U000000000001\",\"MUID\":\"U000000000001\",\"_id\":\"c9b20265-86e3-4f24-917d-74081a3b5496\",\"_rev\":\"1-53f680ef3d2a5b488c5b5f1c091e111a\"}
--ba2576699d9e3222340bd07aa7d345d37c40210046d1a78e592efd6ef9c6
Content-Type: application/json
{\"Date\":\"2019-03-06T17:36:22\",\"CUID\":\"UP000X0000005\",\"MUID\":\"UX00000001003\",\"_id\":\"95361bea-1111-45aa-86c9-f37540911945\",\"_rev\":\"1-551940e668d5c1ad3ef945a28a26b91b\"}
--ba2576699d9e3222340bd07aa7d345d37c40210046d1a78e592efd6ef9c6--

This is the code I used to successfully read this response, and deserialize each of the JSON documents (simplified for readability):

Read Multipart MIME data from HttpResponseMessage in .NET Standard

Now, here’s the catch. In order for ReadAsMultipartAsync() to be available, you will need to install NuGet package Microsoft.AspNet.WebApi.Client.

This is a bit confusing because it seems the extensions that define ReadAsMultipartAsync were defined in System.Net.Http.Formatting package at some point, and that package was later replaced by Microsoft.AspNet.WebApi.Client. Worse, there a few clones of the old package floating around NuGet, so you may inadvertently end up using code which is no longer maintained. Watch out!

--

--

Deep Blue Day

A melomaniac that happens to be in the trenches of software development