I've implemented a file upload method that allows clients to upload to our AWS storage. It looks like this:
[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);
}
}
It works when I make a mock request and unit test. It used to work when I called it from my Linqpad like this:
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();
}
}
But now, whenever I call it from linqpad or postman, It gives me this error:
{
"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)"
}
It looks like the service isn't parsing the Content-Type correctly, but I can't figure out what about it is going wrong. I've stolen the Content-Type from the unit test that worked and put it in the postman request, but it still gives me the above error ^. This is additionally complicated by the fact it doesn't seem to hit any breakpoints when I call the endpoint, it just provides the error and exits. (there is a place in the code that checks the content type, but it's not providing that custom error message).
Can anyone point out what I'm doing wrong here? Thanks in advance!