我在 ASP.NET 上的 POST 有問題。基本上,當我嘗試發布新用戶時,我在郵遞員上得到狀態:“400 Bad Request”,但正在創建用戶!錯誤訊息是: "Value cannot be null。\r\nParameter name: uriString" 。有人可以告訴我為什么會這樣嗎?
我的代碼是:
控制器:
// POST CREATE NEW USER
public IHttpActionResult Post([FromBody] Users User2Insert)
{
try
{
int res = _usersDB.InsertUserToDb(User2Insert);
if (res == -1)
{
return Content(HttpStatusCode.BadRequest, $"User id = {User2Insert.User_ID} was not created in the DB!!!");
}
User2Insert.User_ID = res;
return Created(new Uri(Url.Link("GetUserByID", new { user_id = res })), User2Insert);
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
型號(類):
//INSERT USER
public int InsertUserToDb(Users val)
{
//in case thers already a user with such email
if (GetUserByEmail(val.Email) != null) return -1;
string strComm =
$" INSERT INTO Users(first_name, last_name, email, pass) VALUES("
$" N'{val.First_Name}',"
$" N'{val.Last_Name}',"
$" N'{val.Email}',"
$" N'{val.Pass}'); ";
strComm =
" SELECT SCOPE_IDENTITY() AS[SCOPE_IDENTITY]; ";
return ExcReaderInsertUser(strComm);
}
public int ExcReaderInsertUser(string comm2Run)
{
int UserID = -1;
SqlConnection con = new SqlConnection(strCon);
SqlCommand comm = new SqlCommand(comm2Run, con);
comm.Connection.Open();
SqlDataReader reader = comm.ExecuteReader();
while (reader.Read())
{
UserID = int.Parse(reader["SCOPE_IDENTITY"].ToString());
}
comm.Connection.Close();
return UserID;
}
(我正在使用 SQL)
感謝所有的幫助者
更新(“GetUserByID”的添加代碼:
[Route("{id:int:min(1)}", Name = "GetUserByID")]
public IHttpActionResult Get(int user_id)
{
try
{
Users u = _usersDB.GetUserByID(user_id);
if (u != null)
{
return Ok(u);
}
return Content(HttpStatusCode.NotFound, $"User with id {user_id} was not found!!!");
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
public Users GetUserByID(int user_id)
{
Users u = null;
SqlConnection con = new SqlConnection(strCon);
SqlCommand comm = new SqlCommand(
$" SELECT * FROM Users "
$" WHERE user_id='{user_id}'", con);
comm.Connection.Open();
SqlDataReader reader = comm.ExecuteReader();
if (reader.Read())
{
u = new Users(
(int)reader["user_id"],
(string)reader["first_name"],
(string)reader["last_name"],
(string)reader["email"],
(string)reader["pass"]
);
}
comm.Connection.Close();
return u;
}
uj5u.com熱心網友回復:
如果它在同一個控制器內,請嘗試替換該行
return Created(new Uri(Url.Link("GetUserByID", new { user_id = res })), User2Insert);
這會導致問題,這條線
return Get(res);
或者如果它在不同的控制器中,你可以試試這個
return RedirectToRoute("GetUserByID", new { userId= res });
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/430053.html
標籤:sql 反应 邮政 asp.net-web-api 获取 API
上一篇:SQL查詢WHERE過濾器獨占
下一篇:如何按容器及其日期分組
