415调用文件上传api时不支持的媒体类型

时间:2019-07-19 02:07:00

标签: c# asp.net post file-upload multipartform-data

我已经实现了一种文件上传方法,该方法允许客户端上传到我们的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并将其放入邮递员请求中,但它仍然给我上述错误^。另外,由于在调用端点时似乎没有碰到任何断点,而只是提供了错误并退出,这使情况变得更加复杂。 (代码中有一个检查内容类型的位置,但未提供该自定义错误消息)。

有人可以指出我在做什么错吗?预先感谢!

0 个答案:

没有答案