【发布时间】:2016-03-09 01:02:42
【问题描述】:
我想为我的 webapi 项目上传一个图像,我在 Asp.net MVC 4 中使用 WebImage 类来保存、裁剪、旋转图像。
我在 ApiController 中包含 WebHelper,其功能与 mvc 项目相同 我的问题是在 webapi 项目中,当我在 Webapi 控制器中上传图像时收到错误消息:
{
Message: "An error has occurred."
ExceptionMessage: "No MediaTypeFormatter is available to read an object of type 'WebImage' from content with media type 'multipart/form-data'."
ExceptionType: "System.InvalidOperationException"
StackTrace: " at System.Net.Http.HttpContentExtensions.ReadAsAsync[T](HttpContent content, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger) at System.Net.Http.HttpContentExtensions.ReadAsAsync(HttpContent content, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger) at System.Web.Http.ModelBinding.FormatterParameterBinding.ReadContentAsync(HttpRequestMessage request, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger) at System.Web.Http.ModelBinding.FormatterParameterBinding.ExecuteBindingAsync(ModelMetadataProvider metadataProvider, HttpActionContext actionContext, CancellationToken cancellationToken) at System.Web.Http.Controllers.HttpActionBinding.<>c__DisplayClass1.<ExecuteBindingAsync>b__0(HttpParameterBinding parameterBinder) at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext() at System.Threading.Tasks.TaskHelpers.IterateImpl(IEnumerator`1 enumerator, CancellationToken cancellationToken)"
}
和我的上传方法示例:
[HttpPost]
public HttpResponseMessage filer(WebImage data)
{
HttpResponseMessage response = null;
if (data == null)
{
response = new HttpResponseMessage()
{
Content = new StringContent("Not a image file"),
StatusCode = HttpStatusCode.BadRequest
};
}
else {
response = new HttpResponseMessage()
{
Content = new StringContent(data.FileName.ToString()),
StatusCode = HttpStatusCode.OK
};
}
return response;
}
请解释一下如何添加 MediaTypeFormatter 以支持 WebImage 类。
【问题讨论】:
标签: asp.net asp.net-mvc asp.net-mvc-4 asp.net-web-api asp.net-web-api2