简体   繁体   中英

How to call API using MultiPartFormDataContetnt and get a response in C#

I Have an API that takes an IFormFile and returns an IActionsresult with some values. When i call the API with postman it works fine I get a nice 200 Ok response with the data I am looking for. But when I trie to call the API from within another program I get nothing in response. I get no errors, it's just that the program seems to wait for a response that never shows. I am simply wondering if anyone can see the problem with this code any help would be greately apriciated.

Both my API and my program is on the same computer and here is the code i use to call the 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;
                }
            }
        }
    }

Successful request using postman: Post Request using Postman

Try this-

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();
            }
        }
    }
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM