我正在尝试创建一个Web API,它将获取输入并尝试在SQL数据库中运行Select查询。数据库中的表有三个字段,但我在响应中只需要两个字段。下面是我正在尝试的代码
public async Task<IHttpActionResult> Get(string LabName){
string strcon = ConfigurationManager.ConnectionStrings["CDBConnection"].ConnectionString;
SqlConnection DbConnection = new SqlConnection(strcon);
SqlDataReader reader = null;
DbConnection.Open();
using (SqlCommand command = new SqlCommand("SELECT Acc, CSeq FROM [dbo].[c_Account] WHERE Acc = @AccName", DbConnection))
{
command.Parameters.Add(new SqlParameter("AccName", LabName));
reader = command.ExecuteReader();
List<QueryResult> qresults = new List<QueryResult>();
while (reader.Read())
{
QueryResult qr = new QueryResult();
qr.AccountID = reader["AccountID"].ToString();
qr.CounterSeq = ((int)reader["CounterSeq"]).ToString("000");
qresults.Add(qr);
}
DbConnection.Close();
//build json result
return Ok(qresults);
}
}
这里的问题是它将响应中的所有三个字段拉为
[{"Acc":"xyz","CSeq":"123","Year":null}]
但只是希望响应为
[{"Acc":"xyz","CSeq":"123"}]
也可以返回类似The CSeq associated with Acc xyz is 123
答案 0 :(得分:1)
修改您的myInstanceOfMyClass.doSomethingWithTheContext(getActivity());
模型并将JsonIgnore添加到媒体资源QueryResult
。
Year
我假设您正在为您的web api项目使用json.net(默认)序列化程序。
也可以返回类似
的响应public class QueryResult { [JsonIgnore] public int? Year {get;set;} // guessed the type // the rest of your properties in the model }
您必须向正在返回的模型添加字符串属性,并自行格式化该文本。 Web api框架中没有任何内置功能可以凭空创建人类可读的文本。它应该是你的html /脚本中内置的表示层功能,而不是服务器上的任何东西。