c# - 为什么 HttpResponseMessage 不显示其内容?

标签 c# asp.net-core json.net httpresponse

您好,我正在尝试使用 HttpResponseMessage 发送 Json 对象。 即使在调试时,数据看起来像是在检索 json 时使用 Postman 时插入到 Content 部分(存在 104 字节),但Content 部分没有数据,只有标题。

JsonResponse

{
    "version": {
        "major": 1,
        "minor": 1,
        "build": -1,
        "revision": -1,
        "majorRevision": -1,
        "minorRevision": -1
    },
    "content": {
        "headers": [
            {
                "key": "Content-Type",
                "value": [
                    "text/plain; charset=utf-8"
                ]
            } ////why no data ??
        ]
    },
    "statusCode": 200,
    "reasonPhrase": "OK",
    "headers": [],
    "requestMessage": null,
    "isSuccessStatusCode": true
}

正如您所看到的,没有内容。我重复使用了与早期应用程序中相同的代码,但没有遇到此问题。为什么内容为空?

代码

private static List<User> users = new List<User> {
    new User{ Id = 0, Age = 0, Name = "Failed"},
    new User{ Id = 12, Age = 33, Name = "Daniel"},
    new User{ Id = 13, Age = 33, Name = "Marian"},
};


[HttpGet]
[Route("/api/getusers")]
public async Task<HttpResponseMessage> GetUsers() {
    await Task.Delay(1000);
    var str = JsonConvert.SerializeObject(users);
    return new HttpResponseMessage {
        StatusCode = HttpStatusCode.OK,
        Content = new StringContent(str, Encoding.UTF8)
    };
}

最佳答案

ASP.NET Core 没有内置支持返回 HttpResponseMessage。如果您想返回 JSON,可以使用 IActionResult 并让 ASP.NET Core 为您处理序列化。这是一个更新的示例:

public async Task<IActionResult> GetUsers() {
    await Task.Delay(1000);
    return Json(users);
}

对于您想要允许 content-negotiation 的情况,这里有更多选项, 例如。这是一个支持使用 OkObjectResult 进行内容协商的版本:

public async Task<IActionResult> GetUsers() {
    await Task.Delay(1000);
    return Ok(users);
}

如果您愿意,您甚至可以只返回 users 本身:

public async Task<List<User>> GetUsers() {
    await Task.Delay(1000);
    return users;
}

这应该足以让您开始 - 官方文档进一步解释了事情:Controller action return types in ASP.NET Core Web API .

关于c# - 为什么 HttpResponseMessage 不显示其内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53277049/

相关文章:

c# - 在 LINQ 语句中添加条件

c# - 无 Cookie session

c# - 我们如何在 StringBuilder 中添加字符串?

c# - 检查文件访问权限,获取进程 ID

c# - 如何在 Entity Framework Core 3.1 中对自定义对象执行原始 SQL 查询,而不需要创建表的迁移?

entity-framework - IDomainService 中的 ABP EF Core 多个 DbContext 访问抛出事务错误

c# - 如何使用 Newtonsoft JSON 序列化程序忽略空数组元素

azure - Azure 中的 301 重定向

c# - 反序列化复杂类型但保持选定属性为序列化状态

c# - 覆盖自定义 JSON.net 契约(Contract)解析器中的属性值