You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#中设置HttpResponseMessage.Content后Postman无法查看响应体?

问题原因及解决办法

问题根源

你的控制器没有继承**System.Web.Http.ApiController**,导致Web API框架将HttpResponseMessage当作普通CLR对象序列化,而非解析为真实的HTTP响应返回给客户端——这就是Postman看不到响应体、只能拿到HttpResponseMessage结构序列化结果的原因。

解决步骤

  1. 修正控制器基类
    确保你的控制器继承自System.Web.Http.ApiController(而非MVC的Controller或ASP.NET Core的ControllerBase,适用于传统Web API项目):
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web.Http;

public class DemoController : ApiController // 必须继承ApiController
{
    [HttpGet]
    public HttpResponseMessage MethodName()
    {
        try
        {
            var response = new HttpResponseMessage(HttpStatusCode.OK);
            response.Content = new StringContent("Hello WORLD", Encoding.UTF8, "application/json");
            return response;
        }
        catch (Exception ex)
        {
            var response = new HttpResponseMessage(HttpStatusCode.InternalServerError);
            response.Content = new StringContent($"{{\"error\": \"{ex.Message}\"}}", Encoding.UTF8, "application/json");
            return response;
        }
    }
}
  1. 更推荐的写法
    传统Web API中可以直接使用IHttpActionResult,让框架自动处理响应序列化,代码更简洁:
[HttpGet]
public IHttpActionResult MethodName()
{
    try
    {
        return Ok("Hello WORLD");
    }
    catch (Exception ex)
    {
        return InternalServerError(new Exception(ex.Message));
    }
}

如果是ASP.NET Core项目,建议使用符合Core规范的写法:

using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/[controller]")]
public class DemoController : ControllerBase
{
    [HttpGet]
    public IActionResult MethodName()
    {
        try
        {
            return Ok("Hello WORLD");
        }
        catch (Exception ex)
        {
            return StatusCode(StatusCodes.Status500InternalServerError, new { error = ex.Message });
        }
    }
}

内容的提问来源于stack exchange,提问作者Ayo Adesina

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 00:05:14