如何使用MultiPartFormDataContetnt调用API并在C#中获得响应

时间:2018-06-25 13:06:40

标签: c# asp.net http

我有一个使用IFormFile并返回带有某些值的IActionsresult的API。当我用邮递员调用API时,它可以正常工作,并且我在寻找所需的数据时得到200 OK响应。但是,当我尝试从另一个程序中调用API时,却​​没有任何响应。我没有收到任何错误,只是程序似乎在等待从未显示的响应。我只是想知道是否有人可以看到此代码的问题,因此对您的帮助将非常宝贵。

我的API和程序都在同一台计算机上,这是我用来调用API的代码。

public static async Task<string> Calculate()
    {
        using (var client = new HttpClient())
        {
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            using (var content = new MultipartFormDataContent())
            {
                var img = Image.FromFile("path");
                MemoryStream ms = new MemoryStream();
                img.Save(ms, System.Drawing.Imaging.ImageFormat.jpeg);
                content.Add(new StreamContent(new MemoryStream(ms.ToArray())), "image", "myImage.jpg");
                using (var response = await client.PostAsync($"http://localhost:####/api/1.0/###", content))
                {
                    var responseAsString = await response.Content.ReadAsStringAsync();

                    return responseAsString;
                }
            }
        }
    }

使用邮递员的成功请求: Post Request using Postman

1 个答案:

答案 0 :(得分:0)

试试这个-

using (var client = new HttpClient())
{
    client.BaseAddress = new Uri($"http://localhost/###");
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    using (var content = new MultipartFormDataContent())
    {
        content.Add(new StreamContent(new MemoryStream(image)), "image", "myImage.jpg");
        using (var response = await client.PostAsync($"http://localhost:#####/###/###/###", content).ConfigureAwait(false))
        {
            if (response.StatusCode == HttpStatusCode.OK)
            {
                var responseAsString =  response.Content.ReadAsStringAsync().Result;
                var receiptFromApi = JsonConvert.DeserializeObject<Receipt>(responseAsString);
                var metadata = new metadata(bilaga)
                {
                    Value1 = fromApi.Value1.Value,
                    Value2 = fromApi.Value2.Value,
                    Value3 = fromApi.Value3.Value,
                    Value4 = fromApi.Value4.Value
                };
                return metadata;
            }
            else
            {
                throw new InvalidProgramException();
            }
        }
    }
}

引用-https://blog.stephencleary.com/2012/07/dont-block-on-async-code.html