0

HttpResponseMessage从我的 API 控制器发送如下

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}

为什么我看不到内容?请指教。

4

1 回答 1

0

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

public static string ContentToString(this HttpContent httpContent)
{
    var readAsStringAsync = httpContent.ReadAsStringAsync().GetAwaiter().GetResult();
    return readAsStringAsync;
}

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

于 2022-02-14T20:14:49.567 回答