【问题标题】:How to return a object in HttpResponseMessage in Web api mvc?如何在 Web api mvc 的 HttpResponseMessage 中返回一个对象?
【发布时间】:2017-04-13 08:58:59
【问题描述】:

在我的一个 Get 请求中,我想返回一个包含一些内容的 HttpResponseMessage。目前我的工作方式如下:

// GET api/Account/5
[HttpGet]
[ActionName("GetAccount")]
public HttpResponseMessage GetAccount(int id)
{
    Account value;
    try
    {
        var myque = from x in db.Accounts where x.idUser==id select x;
        value= myque.FirstOrDefault();

    }
    catch (Exception)
    {
        return new HttpResponseMessage { Content = new StringContent("[{\"Success\":\"Fail\"},{\"Message\":\"Login Fail\"}]", System.Text.Encoding.UTF8, "application/json") };
    }
    return new HttpResponseMessage { Content = new StringContent("[{\"Success\":\"Success\"},{\"Message\":\"Login successfully\"}],{\"Data\":"+value+"}", System.Text.Encoding.UTF8, "application/json") };
}

我想为 HttpResponseMessage 添加价值。值将返回一个 json 正常值。

[
    {
    "Success": "Success"
    },
    {
    "Message": "successfully"
    }
    Value will display at here  
]

【问题讨论】:

  • 您不需要返回成功与否的信息。相反,使用 HTTP Code 200 OK 就足够了。
  • 你的意思是:HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, products);返回响应;
  • 是的,Cuong Le 是对的,HttpResponseMessage 设计包含操作是否成功。在此处检查 http 代码 - restapitutorial.com/httpstatuscodes.html 是的,如果您想在响应中传递其他信息,那么您应该将它们添加到响应中
  • 我的客户要求我这样做?
  • @Cuong Le,我正在获取 HTTP 代码 200。但我想从我提供的 URL 读取/访问数据。你能建议我吗...!例如:HttpResponseMessage response = wc.GetAsync(URI).Result;var contents = response.Content.ReadAsStringAsync();我在Contents变量中得到如下结果<html lang="en" dir="ltr" class=" ltr"><head><title>ServiceNow</title><meta http-equiv="X-UA-Compatible" content="chrome=1"></meta><meta http-equiv="cache-control" content="public"></meta><link rel="shortcut icon" href="favicon.ico?v=4"></link>

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


【解决方案1】:

由于您使用的是 [ActionName("GetAccount")]... 您应该使用 IActionResult 作为返回类型。

否则如果要使用HttpResponseMessage,请使用-

[Route("api/GetAccount")]

另外,你可以像这样构造输出结果

return new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = data };

【讨论】:

  • 请编辑您的答案以将代码格式化为代码块,以便于阅读。
猜你喜欢
  • 1970-01-01
  • 2017-07-02
  • 2015-02-21
  • 1970-01-01
  • 1970-01-01
  • 2012-09-19
  • 1970-01-01
  • 2014-05-25
  • 1970-01-01
相关资源
最近更新 更多