Skip to content

Instantly share code, notes, and snippets.

@glennblock
Last active April 4, 2018 20:28
Show Gist options
  • Save glennblock/3768b3a2351ab5c550e3 to your computer and use it in GitHub Desktop.
Save glennblock/3768b3a2351ab5c550e3 to your computer and use it in GitHub Desktop.
mutlpart/mixed response with Web Api
public class TestController : ApiController {
//illustrates how to return multipart/mixed content: http://www.w3.org/Protocols/rfc1341/7_2_Multipart.html
private HttpResponseMessage Get()
{
var friend = GetFriend();
var friendContent = new ObjectContent<Friend>(friend, new JsonMediaTypeFormatter());
var response = new HttpResponseMessage();
//create the multipart content and specify the boundary
var multipartContent = new MultipartContent("mixed", "AaB03x");
//add the friend document
multipartContent.Add(friendContent);
//grab the path for the image and open a stream
var imagePath = GetFilePath(@"images/mamund.jpg");
var file = File.OpenRead(imagePath);
//create the content for the image.
var streamContent = new StreamContent(file);
//set the content type
streamContent.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
//create the disposition header
var disposition = new ContentDispositionHeaderValue("attachment");
disposition.FileName = "mamund.jpg";
streamContent.Headers.ContentDisposition = disposition;
//set the encoding
streamContent.Headers.ContentEncoding.Add("binary");
//add the image content to the multipart content
multipartContent.Add(streamContent);
//set the response content and return it
response.Content = multipartContent;
return response;
}
private string GetFilePath(string sitePath) {
//implement logic to return the path on disk. On IIS you can use Server.MapPath.
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment