Я создал контроллер веб-API и пытаюсь разместить данные в своей базе данных. Когда я тестирую API в POSTMAN, я получаю результат 200 OK, но false
возврат для тела.
Я попытался изменить вместо [FormBody]
, но это тоже не работает.
Я добавил метод в качестве логического значения для проверки, но я просто получаю false.
Вот фактическая ссылка на опубликованный API:
Добавить API и Все данные
Вот что я попробовал в 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);
}
}
}
City.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;
}
}
}
Я ожидаю, что данные будут добавлены в фактическую базу данных.