【发布时间】:2014-12-10 21:37:37
【问题描述】:
我正在尝试找出在 .Net 4.0 上使用 Web API 返回空结果的正确方法
我不能使用 IHttpResult,因为那是 .net 4.5 的 WebApi 的一部分
Ok(ResultType.NoResult);
是我以前使用的函数,但现在我有这个块,它返回我的模型而不是 IHttpResult。返回空结果的正确方法是什么?
public Models.Login Post(Models.LoginInfo loginInfo)
{
if(!ModelState.IsValid)
{
//throw new HttpResponseException("Failed");
}
//Fake Sql Stuff happened here. Dont question it.
try
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = @"fakeconnectionstring";
conn.Open();
SqlCommand cmd = new SqlCommand("LoginQuery", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@username", loginInfo.Username);
cmd.Parameters.AddWithValue("@password", loginInfo.Password);
SqlDataReader reader = cmd.ExecuteReader();
Models.Login login = new Models.Login();
// Call Read before accessing data.
while (reader.Read())
{
login.id = (int)reader["id"];
login.Username = reader["username"].ToString();
login.Password = reader["password"].ToString();
login.Firstname = reader["first_name"].ToString();
login.Lastname = reader["last_name"].ToString();
}
conn.Close();
//return Ok(ResultType.NoResult);
//How to return empty result
}
catch
{
//throw new HttpResponseException(HttpStatusCode.NotFound);
//How Do I Throw an empty result
}
}
【问题讨论】:
标签: c# asp.net asp.net-mvc asp.net-mvc-4 asp.net-web-api