【问题标题】:WebAPI POST working but not adding to the database?WebAPI POST 工作但不添加到数据库?
【发布时间】:2019-08-22 06:01:56
【问题描述】:

我创建了一个 Web API 控制器并尝试将数据发布到我的数据库。当我在 POSTMAN 中测试 API 时,我得到一个 200 OK Result 但一个 false 返回正文。

我尝试从[FormBody] 更改,但这也不起作用。 我已将该方法添加为布尔值以进行检查,但我只收到 false。

这是一个已发布 api 的实际链接: Add API 和 All data

这是我在 POSTMAN 中尝试使用 Body -> raw -> JSON/Application

{
    CityName: "Test1",
    State: "PA",
    Population: "0",
    MHouseholdIncome: "0",
    POwnerRenter: "0",
    MHomeValue: "0",
    MAge: "0",
    UnemploymentRate: "0",
    CrimeIndex: "0"
}

这是我的控制器:

// POST: api/Cities/AddCity
        [HttpPost()]
        [HttpPost("AddCity")]
        public Boolean AddCity([FromBody]City city)
        {
            if (city != null)
            {
                DBConnect objDB = new DBConnect();
                SqlCommand objCmd = new SqlCommand();

                objCmd.CommandType = CommandType.StoredProcedure;
                objCmd.CommandText = "AddCity";

                objCmd.Parameters.AddWithValue("@theCity", city.CityName);
                objCmd.Parameters.AddWithValue("@theState", city.State);
                objCmd.Parameters.AddWithValue("@thePopulation", city.Population);
                objCmd.Parameters.AddWithValue("@theIncome", city.MHouseholdIncome);
                objCmd.Parameters.AddWithValue("@theOwner", city.POwnerRenter);
                objCmd.Parameters.AddWithValue("@theHomeValue", city.MHomeValue);
                objCmd.Parameters.AddWithValue("@theMedianAge", city.MAge);
                objCmd.Parameters.AddWithValue("@theUnemploymentRate", city.UnemploymentRate);
                objCmd.Parameters.AddWithValue("@theCrime", city.CrimeIndex);

                int value = objDB.DoUpdateUsingCmdObj(objCmd);

                if (value > 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }

这是我的代码:

protected void btnAdd_Click(object sender, EventArgs e)
        {
            City city = new City();

            city.CityName = txtCity.Text;
            city.State = ddStates.SelectedValue;
            city.Population = int.Parse(txtPopulation.Text);
            city.MHouseholdIncome = float.Parse(txtHouseholdIncome.Text);
            city.POwnerRenter = float.Parse(txtOwnerRenter.Text);
            city.MHomeValue = float.Parse(txtHomeValue.Text);
            city.MAge = float.Parse(txtAge.Text);
            city.UnemploymentRate = float.Parse(txtUnemploymentRate.Text);
            city.CrimeIndex = float.Parse(txtCrimeIndex.Text);

            JavaScriptSerializer js = new JavaScriptSerializer();
            String jsonCity = js.Serialize(city);

            try
            {
                WebRequest request = WebRequest.Create(webApiUrl + "AddCity/");
                request.Method = "POST";
                request.ContentLength = jsonCity.Length;
                request.ContentType = "application/json";

                StreamWriter writer = new StreamWriter(request.GetRequestStream());
                writer.Write(jsonCity);
                writer.Flush();
                writer.Close();

                WebResponse response = request.GetResponse();
                Stream dataStream = response.GetResponseStream();
                StreamReader reader = new StreamReader(dataStream);
                String data = reader.ReadToEnd();
                reader.Close();
                response.Close();

                if (data == "true")
                {
                    string msg = "The city was successfully added to the database.";
                    ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + msg + "');", true);
                }
                else
                {
                    string msg = "A problem occured while adding the city to the database. The data was not recorded.";
                    ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + msg + "');", true);
                }
            }
            catch (Exception ex)
            {
                string msg = "Error:" + ex.Message;
                ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + msg + "');", true);
            }
        }
    }

城市.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CityLibrary
{
    public class City
    {
        public int CityID { get; set; }
        public string CityName { get; set; }
        public string State { get; set; }
        public int Population { get; set; }
        public float MHouseholdIncome { get; set; }
        public float POwnerRenter { get; set; }
        public float MHomeValue { get; set; }
        public float MAge { get; set; }
        public float UnemploymentRate { get; set; }
        public float CrimeIndex { get; set; }

        public City()
        {

        }

        public City(int id, string name, string state, int ppl, float income,
            float owner, float home, float age, float rate, float crime)
        {
            this.CityID = id;
            this.CityName = name;
            this.State = state;
            this.Population = ppl;
            this.MHouseholdIncome = income;
            this.POwnerRenter = owner;
            this.MHomeValue = home;
            this.MAge = age;
            this.UnemploymentRate = rate;
            this.CrimeIndex = crime;
        }
    }
}

我希望将数据添加到实际数据库中。

【问题讨论】:

  • 尝试调试您的代码并在线添加断点 => int value = objDB.DoUpdateUsingCmdObj(objCmd); 并让我知道 value 变量中的值。
  • 我无法以这种方式调试它,因为它们位于两个不同的 asp.net 项目上,但是当我调试实际页面时,我的响应、阅读器和其他所有内容都为空,但我的 jsonCity 是正确的. @er-sho
  • @pyuntae 能否把City模型类的代码也发一下。另外,您是否通过浏览表本身确认数据没有添加到数据库表中?
  • @MohsinMehmood 我刚刚发布。是的,我已经确认了。我还确认我的存储过程确实有效。
  • 为了缩小问题范围,更新控制器操作代码,如:if(city==null) { throw new Exception("City parameter is null"); } 我怀疑传递给控制器​​方法的 json 没有反序列化为 City 对象。

标签: c# asp.net asp.net-web-api postman


【解决方案1】:

检查 objCmd 是否为 null,如果没有,检查 DoUpdateUsingCmdObj 方法

【讨论】:

  • 就像我说的它返回 false
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-28
  • 2020-10-25
  • 2017-03-07
  • 1970-01-01
  • 2019-11-16
  • 2018-02-06
相关资源
最近更新 更多