首页 > 解决方案 > 415 调用文件上传api时不支持的媒体类型

问题描述

我实现了一种文件上传方法,允许客户端上传到我们的 AWS 存储。它看起来像这样:

        [HttpPost]
        [Route("api/AWS/UploadToTemp")]
        public async Task<HttpResponseMessage> UploadToTempAsync(Stream stream)
        {
            HttpClient client = new HttpClient();
            HttpRequestMessage req = new HttpRequestMessage();
            req.Properties[HttpPropertyKeys.HttpConfigurationKey] = httpConfig;

            try
            {
                var token = HttpContextManager.Current.Response.ClientDisconnectedToken;
                var (attachmentStream, contentType, length) = await StreamHandler.ExtractStreamAndParamsAsync(stream, token).ConfigureAwait(false);
                var guid = await UploadFileAsync(contentType, attachmentStream, length, token);
                JObject json = new JObject();
                json.Add("AttachmentGuid", guid);
                return req.CreateResponse(HttpStatusCode.OK, json);
            }
            catch (Exception e)
            {
                while (e.Message.Contains("see inner exception"))
                {
                    e = e.InnerException;
                }
                return req.CreateErrorResponse(HttpStatusCode.InternalServerError, e.Message);
            }
        }

当我发出模拟请求和单元测试时,它可以工作。当我像这样从我的 Linqpad 调用它时,它曾经工作过:

using (var httpClient = new HttpClient())
{
    MultipartFormDataContent form = new MultipartFormDataContent();
    var bytes = File.ReadAllBytes(filePath);

    form.Add(new ByteArrayContent(bytes)
    {
        Headers =
        {
            ContentLength = bytes.Length,
            ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType)
        }
    }, "notused", "not.used");

    using (var response = await httpClient.PostAsync("http://localhost:52655/api/AWS/UploadToTemp", form))
    {
        response.EnsureSuccessStatusCode();
    }
}

但是现在,每当我从 linqpad 或邮递员调用它时,它都会给我这个错误:

{
    "Message": "The request entity's media type 'multipart/form-data' is not supported for this resource.",
    "ExceptionMessage": "No MediaTypeFormatter is available to read an object of type 'Stream' from content with media type 'multipart/form-data'.",
    "ExceptionType": "System.Net.Http.UnsupportedMediaTypeException",
    "StackTrace": "   at System.Net.Http.HttpContentExtensions.ReadAsAsync[T](HttpContent content, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)\r\n   at System.Web.Http.ModelBinding.FormatterParameterBinding.ReadContentAsync(HttpRequestMessage request, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)"
}

看起来该服务没有正确解析 Content-Type,但我不知道它出了什么问题。我从有效的单元测试中窃取了 Content-Type 并将其放入邮递员请求中,但它仍然给了我上述错误^。这也很复杂,因为当我调用端点时它似乎没有遇到任何断点,它只是提供错误并退出。(代码中有一个地方检查内容类型,但它没有提供该自定义错误消息)。

谁能指出我在这里做错了什么?提前致谢!

标签: c#asp.netpostfile-uploadmultipartform-data

解决方案


推荐阅读