Last active
April 4, 2018 20:28
-
-
Save glennblock/3768b3a2351ab5c550e3 to your computer and use it in GitHub Desktop.
mutlpart/mixed response with Web Api
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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