【问题标题】:How to see HttpResponseMessage client side?如何查看 HttpResponseMessage 客户端?
【发布时间】:2016-06-13 08:35:50
【问题描述】:

我是一位经验丰富的程序员,但对 WebApi 很陌生(我们使用的是 MS asp.net mvc 框架)。

客户要求将所有返回值包装在此类对象中:

{
  success: [boolean],
  errorLog: [error message, if failed],
  referer: [api call details],
  payload: {
    // results, if success
}

我看到标准已经要求返回一个包含此信息的 HttpResponseMessage 对象。因此,我没有重复,而是只返回一个这种类型的对象(直接返回,或者通过 IHttpActionResult,例如

return Ok(object);

但是,我看不到如何从客户端使用此对象。当我从浏览器进行 api 调用时,我看到的只是内容(即使使用调试器)。当我返回错误时,我看到:

 <Error>
    <Message>foo bar</Message>
 </Error>

但没有其他信息的迹象(StatusCode、ReasonPhrase 等)。如果我返回 Json 格式,同样适用。

这个对象是否在沿线某处被“剥离”,如果是这样,由谁“剥离”?我怎样才能让这个对象到达 api 调用者,以便他/她可以使用所有关联的字段?

谢谢

编辑:根据评论的要求,我发布了我的服务器端代码,尽管内容不多。我尝试查看 HttpResponseMessage 对象是创建此控制器:

public HttpResponseMessage Get() {
            HttpResponseMessage response = Request.CreateErrorResponse(HttpStatusCode.NotAcceptable, "foo bar");
            response.ReasonPhrase = "There is no reason.";
            return response;
        }

这是导致上面发布的 xml 的代码。

【问题讨论】:

  • 应该不是这样,你能发布你的服务器端代码吗?

标签: c# asp.net-mvc asp.net-web-api


【解决方案1】:

Is this object 'stripped' somewhere along the line, and if so by who? 当您返回 IHttpActionResult 调用 ExecuteAync 以创建 HttpResponseMessage 时,该对象将在后台被 HttpResponseMessage 剥离。 因此,为了查看所有字段,您应该在原始模式下使用诸如 fiddler 之类的工具,或者在 chrome 中使用诸如 HttpHeader 之类的扩展名。 How can I allow this object to arrive to the api caller so s/he can use all the associated fields
发送预期答案的一种方法是创建这样的 POCO

 public class Payload
    {
    }

    public class CustomResponse
    {
        public IList<bool> Success { get; set; }
        public IList<string> ErrorLog { get; set; }
        public IList<string> Referer { get; set; }
        public Payload Payload { get; set; }
    }

并像这样发送答案

 return OK(new CustomObject(){Payload=yourObject});

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2014-02-09
  • 1970-01-01
  • 2011-05-27
  • 2022-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-14
相关资源
最近更新 更多