[英]How to call API using MultiPartFormDataContetnt and get a response in C#
我有一個使用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;
}
}
}
}
使用郵遞員的成功請求:使用郵遞員的請求
嘗試這個-
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.