首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从HttpContent中读取HttpResponseMessage

从HttpContent中读取HttpResponseMessage
EN

Stack Overflow用户
提问于 2017-12-25 19:23:31
回答 1查看 742关注 0票数 0

我从API控制器发送HttpResponseMessage如下所示

代码语言:javascript
复制
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-创建一个扩展方法

代码语言:javascript
复制
public static string ContentToString(this HttpContent httpContent)
{
    var readAsStringAsync = httpContent.ReadAsStringAsync();
    return readAsStringAsync.Result;
}

阅读内容如下

代码语言:javascript
复制
var av = result.Content.ContentToString();

输出

代码语言:javascript
复制
{"result":null,"targetUrl":null,"success":true,"error":null,"unAuthorizedRequest":false,"__abp":true}

为什么我不知道内容?请给我建议。

EN

回答 1

Stack Overflow用户

发布于 2022-02-14 20:14:49

由于调用httpContent.ReadAsStringAsync()返回一个Task<string>,我建议添加一个侍者,如下所示:

代码语言:javascript
复制
public static string ContentToString(this HttpContent httpContent)
{
    var readAsStringAsync = httpContent.ReadAsStringAsync().GetAwaiter().GetResult();
    return readAsStringAsync;
}

或者,更新您的调用代码以处理async调用,这样它就可以直接await ReadAsStringAsync方法。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47971438

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档