【发布时间】: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