我从API控制器发送HttpResponseMessage如下所示
public HttpResponseMessage Upload()
{
HttpResponseMessage response = new HttpResponseMessage();
HttpRequestMessage request = new HttpRequestMessage();
if (System.Web.HttpContext.Current.Request.Files.Count > 0)
{
var file = System.Web.HttpContext.Current.Request.Files[0];
var path = System.Web.Hosting.HostingEnvironment.MapPath("----------");
bool folderExists = Directory.Exists(path);
if (!folderExists)
Directory.CreateDirectory(path);
string pathWithFileName = Path.Combine(path, file.FileName);
file.SaveAs(pathWithFileName);
response.StatusCode = HttpStatusCode.Created;
response.Content = new StringContent(pathWithFileName, System.Text.Encoding.UTF8, "application/json");
response.Content = new JsonContent(new
{
Name = "a",
Address = "b",
Message = "Any Message"
});
return response;
}
else
{
response.StatusCode = HttpStatusCode.BadRequest;
return response;
}
}我试图按以下方式阅读内容
1-创建一个扩展方法
public static string ContentToString(this HttpContent httpContent)
{
var readAsStringAsync = httpContent.ReadAsStringAsync();
return readAsStringAsync.Result;
}阅读内容如下
var av = result.Content.ContentToString();输出
{"result":null,"targetUrl":null,"success":true,"error":null,"unAuthorizedRequest":false,"__abp":true}为什么我不知道内容?请给我建议。
发布于 2022-02-14 20:14:49
由于调用httpContent.ReadAsStringAsync()返回一个Task<string>,我建议添加一个侍者,如下所示:
public static string ContentToString(this HttpContent httpContent)
{
var readAsStringAsync = httpContent.ReadAsStringAsync().GetAwaiter().GetResult();
return readAsStringAsync;
}或者,更新您的调用代码以处理async调用,这样它就可以直接await ReadAsStringAsync方法。
https://stackoverflow.com/questions/47971438
复制相似问题