使用post方法向Webapi发送请求时,不支持的媒体类型异常

时间:2017-10-31 11:48:18

标签: c# api asp.net-web-api

我正在尝试将图片上传到服务器,但我得到了不支持的媒体类型异常'。在这里,我尝试上传图像字节为dto,我正在使用postmethod。这是我正在使用的示例代码。

上传图片到服务器的示例代码:

json_st['results']['address_components']
Traceback (most recent call last):

  File "<ipython-input-94-315fa8711f9d>", line 1, in <module>
    json_st['results']['address_components']

TypeError: list indices must be integers or slices, not str

服务器方法:

ORDER BY msg_id

Dto课程:

public static async Task<T> UploadProfilePic<T>(string apiUrl, FileDto fileDto)
{
    try
    {
        using (var httpClient = new HttpClient())
        {
            httpClient.BaseAddress = new Uri(ApplicationApiUrls.AppWebUrl);

            httpClient.DefaultRequestHeaders.Accept.Clear();

            httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + ApplicationContext.AccessToken);

            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));//ACCEPT header

            string filename = fileDto.FileName;

            MultipartFormDataContent content = new MultipartFormDataContent();
            ByteArrayContent imageContent = new ByteArrayContent(fileDto.ImageBytes);

            imageContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName = filename
            };

            content.Add(imageContent);

            var response = await httpClient.PostAsync(new Uri(ApplicationApiUrls.AppWebUrl + apiUrl), content);

            var stringAsync = await response.Content.ReadAsStringAsync();

            if (response.IsSuccessStatusCode)
            {
                var responseJson = stringAsync;

                return JsonConvert.DeserializeObject<T>(responseJson);
            }

            LoggingManager.Error("Received error response: " + stringAsync);
            return default(T);
        }
    }
    catch(Exception ex)
    {
        return default(T);
    }
}

enter image description here

我在服务器中使用post方法来保存图像。请提出任何想法,我缺少什么。

1 个答案:

答案 0 :(得分:0)

默认情况下,Web Api不支持“multipart / form-data”媒体类型(您发送)。所以你需要process the request body directly 我已经更新了你的服务器方法。现在它可以读取已发送的文件

[HttpPost]
[ActionName("UpdateProfilePicFromMobile")]
public ResponseViewModel UpdateProfilePicFromMobile()
{
    try
    {
        int userId = User.Identity.GetUserId<int>();

        var file = HttpContext.Current.Request.Files.Count > 0 ? HttpContext.Current.Request.Files[0] : null;

        if (userId > 0 && file?.ContentLength > 0)
        {
            var imageManager = new ImageManager();
            imageManager.SaveImage(file.InputStream, file.FileName, ImageTypes.ProfilePicture);

            return new ResponseViewModel() { success = true, id = pid.ToString(), message = "Image updated successfully." };
        }

        return new ResponseViewModel() { success = false, id = "", message = "Sorry, Image faile to update." };
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex);

        return new ResponseViewModel() { success = false, id = "", message = "Sorry, Image faile to update." + "/ " + ex.Message };
    }
}