I am trying to create a Web API which will get an input and tries to run Select query in SQL Database. The table in the DB has three fields but I need only two fields in the response.Below is the code I am trying
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);
}
}
The issue here is it pulls all the three fields in the response as
[{"Acc":"xyz","CSeq":"123","Year":null}]
But just expecting the response as
[{"Acc":"xyz","CSeq":"123"}]
Also is it possible to return the response something like The CSeq associated with Acc xyz is 123
OkNegotiatedContentResult<T>(via method Ok) so the caller determines the content type with the http headercontent-type. Web api (with the default configuration) will automatically generate a json result from the passed in model using json.net (another default) as the serializer.