【问题标题】:How do I return an empty result using MVC WebApi 4如何使用 MVC WebApi 4 返回一个空结果
【发布时间】: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


    【解决方案1】:

    通常null 没有任何意义:

    {
     ...
     return null; 
    }
    catch
    {
       return null;
    }
    

    编程注意事项:不处理异常(例如吞下异常)是您的应用程序潜在的无声杀手。

    【讨论】:

      【解决方案2】:

      最佳实践表明 POST 仅应在更改数据/模型的状态时使用。如果您希望在 POST 调用后返回一些数据,您可以通过重定向到另一个操作来使用“Post-Redirect-Get”模式。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-20
        • 2017-05-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多