Рассмотрим веб-службу, написанную в ASP.NET Web API, чтобы принимать любые числовые файлы в виде "многочастного/смешанного" запроса. Макет вспомогательного метода выглядит следующим образом (предполагается, что _client
является экземпляром System.Net.Http.HttpClient
):
public T Post<T>(string requestUri, T value, params Stream[] streams)
{
var requestMessage = new HttpRequestMessage();
var objectContent = requestMessage.CreateContent(
value,
MediaTypeHeaderValue.Parse("application/json"),
new MediaTypeFormatter[] {new JsonMediaTypeFormatter()},
new FormatterSelector());
var content = new MultipartContent();
content.Add(objectContent);
foreach (var stream in streams)
{
var streamContent = new StreamContent(stream);
streamContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
streamContent.Headers.ContentDisposition =
new ContentDispositionHeaderValue("form-data")
{
Name = "file",
FileName = "mystream.doc"
};
content.Add(streamContent);
}
return _httpClient.PostAsync(requestUri, content)
.ContinueWith(t => t.Result.Content.ReadAsAsync<T>()).Unwrap().Result;
}
Метод, который принимает запрос в подклассе ApiController, имеет подпись следующим образом:
public HttpResponseMessage Post(HttpRequestMessage request)
{
/* parse request using MultipartFormDataStreamProvider */
}
В идеале, я хотел бы определить его так, чтобы контакт, источник и цель были извлечены из содержимого "multipart/mixed" на основе свойства "name" заголовка Content-Disposition.
public HttpResponseMessage Post(Contact contact, Stream source, Stream target)
{
// process contact, source and target
}
Однако, с моей существующей сигнатурой, отправка данных на сервер приводит к InvalidOperationException
с сообщением об ошибке:
Нет "MediaTypeFormatter" доступно для чтения объекта типа "HttpRequestMessage" с типом мультимедиа "multipart/mixed".
В Интернете есть несколько примеров того, как отправлять и получать файлы с использованием ASP.NET Web API и HttpClient. Тем не менее, я не нашел ничего такого, чтобы показать, как справиться с этой проблемой.
Я начал изучать реализацию пользовательского MediaTypeFormatter
и зарегистрировать его с глобальной конфигурацией. Тем не менее, в то время как легко обрабатывать сериализацию XML и JSON в пользовательском MediaTypeFormatter
, неясно, как бороться с "многочастными/смешанными" запросами, которые могут быть в значительной степени чем-то.