【问题标题】:Deleting row by id not working in Asp.net core web API + Angular 9按 ID 删除行在 Asp.net 核心 Web API + Angular 9 中不起作用
【发布时间】: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


【解决方案1】:

您的route 路径已被此属性[HttpDelete("{id}")] 覆盖

所以只需删除 Route 属性并像这样添加您的属性

[HttpDelete("DeleteById/{id}")]

接下来需要去掉方法参数中的[FromBody]属性,这样写

public IActionResult DeleteSettlementById(int id)

希望对您有所帮助 - 编码愉快 :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-17
    • 2016-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多