【发布时间】:2021-02-01 07:14:55
【问题描述】:
我试图通过将 Angular 9+ 中的 id 传递给 ASP.NET Core Web API 来删除该列,但我无法访问控制器。我在这里犯了什么错误?我正在使用表数据来运行 SQL 查询。
控制器
[Route("api/[controller]")]
[ApiController]
public class SettlementController : ControllerBase
{
public IConfiguration Configuration { get; }
private readonly DatabaseContext _context;
public SettlementController(IConfiguration configuration, DatabaseContext context)
{
Configuration = configuration;
_context = context;
}
// Delete settlement by id
[Route("DeleteById")]
[HttpDelete("{id}")]
public IActionResult DeleteSettlementById([FromBody] SettlementModel model) //sealed class of having Id only
{
var tid = model.Id;
try
{
string sConn = Configuration["ConnectionStrings:ServerConnection"];
using (SqlConnection con = new SqlConnection(sConn))
{
List<Object> objList = new List<Object>();
// This is the stored procedure. I pass in the "Id"
string query = "ST_PRO_DELETESETTLEMENT";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@TID", SqlDbType.VarChar).Value = tid;
con.Open();
cmd.Connection = con;
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
objList.Add(new
{
//TID = reader[0].ToString(),
});
}
}
con.Close();
}
return Ok(objList);
}
}
catch (Exception ex)
{
throw ex;
}
}
settlementService.ts 文件:
deleteSettlement(id) {
console.log(id);
return this.http.delete(this.BaseURL + 'Settlement/DeleteById/' + id);
}
打字稿文件:
deleteSettle(tid) {
console.log(tid); // getting tid in console
if (confirm('Are you sure to delete this record ? TID: '+ tid)) {
this.settlementService.deleteSettlement(tid).subscribe(
(data: any) => {
this.toastr.success("Successfully deleted");
},
err => {
if (err.status == 400)
this.toastr.error('Server error or bad request', 'Error');
else
this.toastr.error('Failed to check data', 'Server Error');
}
);
}
}
错误:
删除 https://localhost:44372/api/Settlement/DeleteById/355 404
【问题讨论】:
-
如果您有一个在数据库中执行
DELETE的存储过程 - 为什么您使用的是ExecuteReader??这完全没有意义——你不会期望返回一个需要读取的结果集......只需使用ExecuteNonQuery()代替!另外:您应该在 before 上使用.Open()将连接分配给SqlCommand对象 - 最好在构造函数中 -
this.BaseURL对于从角度调用的其他 api 具有相同的值?你可以从邮递员那里调用这个 API 吗? -
除了 marc_s 注释 - 调用
ExecuteNonQuery将返回受 SQL 语句影响的行数,因此如果您想要确认该行已被实际删除,您可以简单地检查 ExecuteNonQuery 是否返回一个正值。 -
@ChetanRanpariya this.BaseURL 也是相同的值。 PostMan 错误:415 不支持的媒体类型
标签: asp.net angular asp.net-core asp.net-web-api angular9