- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
考虑使用 ASP.NET Web API 编写的 Web 服务来接受任意数量的文件作为“多部分/混合”请求。辅助方法如下所示(假设 _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 */
}
理想情况下,我想这样定义它,其中根据“Content-Disposition” header 的“name”属性从“multipart/mixed”内容中提取联系人、源和目标。
public HttpResponseMessage Post(Contact contact, Stream source, Stream target)
{
// process contact, source and target
}
但是,使用我现有的签名,将数据发布到服务器会导致 InvalidOperationException
并显示以下错误消息:
No 'MediaTypeFormatter' is available to read an object of type 'HttpRequestMessage' with the media type 'multipart/mixed'.
互联网上有许多如何使用 ASP.NET Web API 和 HttpClient 发送和接收文件的示例。但是,我还没有找到任何说明如何处理此问题的方法。
我开始考虑实现自定义 MediaTypeFormatter
并将其注册到全局配置中。然而,虽然在自定义 MediaTypeFormatter
中处理序列化 XML 和 JSON 很容易,但尚不清楚如何处理几乎可以是任何内容的“多部分/混合”请求。
最佳答案
看看这个论坛:http://forums.asp.net/t/1777847.aspx/1?MVC4+Beta+Web+API+and+multipart+form+data
下面是一段代码(由 imran_ku07 发布),可以帮助您实现自定义格式化程序来处理多部分/表单数据:
public class MultiFormDataMediaTypeFormatter : FormUrlEncodedMediaTypeFormatter
{
public MultiFormDataMediaTypeFormatter() : base()
{
this.SupportedMediaTypes.Add(new MediaTypeHeaderValue("multipart/form-data"));
}
protected override bool CanReadType(Type type)
{
return true;
}
protected override bool CanWriteType(Type type)
{
return false;
}
protected override Task<object> OnReadFromStreamAsync(Type type, Stream stream, HttpContentHeaders contentHeaders, FormatterContext formatterContext)
{
var contents = formatterContext.Request.Content.ReadAsMultipartAsync().Result;
return Task.Factory.StartNew<object>(() =>
{
return new MultiFormKeyValueModel(contents);
});
}
class MultiFormKeyValueModel : IKeyValueModel
{
IEnumerable<HttpContent> _contents;
public MultiFormKeyValueModel(IEnumerable<HttpContent> contents)
{
_contents = contents;
}
public IEnumerable<string> Keys
{
get
{
return _contents.Cast<string>();
}
}
public bool TryGetValue(string key, out object value)
{
value = _contents.FirstDispositionNameOrDefault(key).ReadAsStringAsync().Result;
return true;
}
}
}
然后您需要将此格式化程序添加到您的应用程序中。如果进行自托管,您只需添加以下内容即可:
config.Formatters.Insert(0, new MultiFormDataMediaTypeFormatter());
在实例化 HttpSelfHostServer 类之前。
--编辑--
要解析二进制流,您需要另一个格式化程序。这是我在我的一个工作项目中用来解析图像的一个。
class JpegFormatter : MediaTypeFormatter
{
protected override bool CanReadType(Type type)
{
return (type == typeof(Binary));
}
protected override bool CanWriteType(Type type)
{
return false;
}
public JpegFormatter()
{
SupportedMediaTypes.Add(new MediaTypeHeaderValue("image/jpeg"));
SupportedMediaTypes.Add(new MediaTypeHeaderValue("image/jpg"));
SupportedMediaTypes.Add(new MediaTypeHeaderValue("image/png"));
}
protected override Task<object> OnReadFromStreamAsync(Type type, Stream stream, HttpContentHeaders contentHeaders, FormatterContext formatterContext)
{
return Task.Factory.StartNew(() =>
{
byte[] fileBytes = new byte[stream.Length];
stream.Read(fileBytes, 0, (int)fileBytes.Length);
return (object)new Binary(fileBytes);
});
}
protected override Task OnWriteToStreamAsync(Type type, object value, Stream stream, HttpContentHeaders contentHeaders, FormatterContext formatterContext, TransportContext transportContext)
{
throw new NotImplementedException();
}
}
在您的 Controller /操作中,您需要执行以下操作:
public HttpResponseMessage UploadImage(Binary File) {
//do something with your file
}
关于c#-4.0 - 如何正确实现 MediaTypeFormatter 来处理 'multipart/mixed' 类型的请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10036445/
我已经编写了一个 ServiceHelper 类,它将协助 POST 到 C# Web API Controller public class ServiceHelper : IServiceHelp
我正在尝试根据请求的 URL 输出不同格式的类型。在 Preview5 之前,我执行了以下操作以在 MediaTypeFormatters OnWriteToStream-Method 中获取 URI
我有一个 web api,其中全局配置被配置为使用:XmlMediaTypeFormatter 我的问题是我不会用一个新的 Controller 扩展这个 web api,而是使用 JsonMedia
我有 extended the JsonMediaTypeFormatter 为了在 JSON 中为 decorated with a custom attribute 的类型生成“根”对象. 我将如
我在服务器上部署了一个 webapi 项目 mvc4 rc 和一个 mvc4 rc web 应用程序。 在本地一切正常,但在服务器上出现错误 2012-06-09 03:18:18,659 [23]
我有一个带有自定义 MediaTypeFormatter 的自托管 WebApi 应用程序 根据“名称”参数(或 URL 的一部分),应用程序应将请求正文格式化为不同的类型。 这是 Action //
AJAX 调用 $.ajax({ url: '/api/Inventory', cache: false, type: 'POST', data: json,
考虑这段代码: public Gender Get() { return Gender.Female; } public enum Gender { Male, Female }
我在 TestFormatter.cs extending MediaTypeFormatter 中有一个名为 TestFormatter 的自定义媒体格式化程序。现在我想添加这个格式化程序。一种选择
我有一个 MVC 5 Web Api 和一个连接到它的桌面应用程序。 我有一个 Controller 并从应用程序连接到它没有任何问题,但是当我将 [Authorize] 属性放入 Controlle
我有一个非常简单的 ApiController,它在 Win7 上运行良好,但在 Windows 2003 Server 上我遇到错误。 获取请求(来自浏览器或 $.getJson): https:/
我正在实现我自己的 MediaTypeFormatter我对方法有一些疑问 WriteToStreamAsync对于我正在做的自定义 XML 序列化程序: public override Task W
我创建了一个 WebAPI 项目来帮助捕获 TinCan 学习类(class)中的语句,但我在检索任何请求负载详细信息时遇到了极大的困难。在此有效负载中,我传递了我试图捕获的整个语句,但在尝试使用以下
我正在尝试自定义实现 MediaTypeFormatter , 但方法 bool CanReadType(Type type)总是以 IKeyValueModel 类型调用,而不是我的类型 MyPro
考虑使用 ASP.NET Web API 编写的 Web 服务来接受任意数量的文件作为“多部分/混合”请求。辅助方法如下所示(假设 _client 是 System.Net.Http.HttpClie
我正在使用 ASP.NET Web API。我的 Controller 中有一个 Action ,如果没有参数,它可以正常工作。如果有一个参数,例如: public string UploadFile
我正在为 HTML 编写媒体类型格式化程序,以根据用户的 html 请求自动生成 Razor View 。我这样做是为了在 SelfHosted 服务中使用。我需要检测请求了哪些 Controller
当我尝试使用 ASP.NET WEBAPI 将我的表单数据发布到 JSON 文件时,我收到“没有 MediaTypeFormatter 可用于从媒体类型为‘text/plain’的内容中读取类型为‘P
我有一个 ASP.Net WebAPI 项目将返回 JSON,但特别是 HAL+JSON。我知道我可以编写自定义 MediaTypeFormatter 来执行此操作,但我计划返回相同的 HAL 格式响
情况是这样的: 它们是 Servoy 中的外部 Web 服务,我想在 ASP.NET MVC 应用程序中使用此服务。 通过这段代码,我尝试从服务中获取数据: HttpResponseMessage r
我是一名优秀的程序员,十分优秀!