【问题标题】:How to handle duplicate records in Asp.net Web API如何处理 Asp.net Web API 中的重复记录
【发布时间】:2022-01-20 16:20:38
【问题描述】:

我已经使用 ASP.net 实现了 CRUD 操作。每个 API 方法都可以正常工作,但问题是,在前端 - 如果有人放置相同的主键,它会给出一个明显的特定异常错误。各位可以看一下代码sn-p:

[HttpPost]
        [Route("~/api/feestable/Registerfees")]
        public HttpResponseMessage Registerfees(feestable fee)
        {
            var response = Request.CreateResponse(HttpStatusCode.OK);
            DataTable table = new DataTable();
            string myconnection = ConfigurationManager.AppSettings["mycon"];
            try
            {
                using (SqlConnection con = new SqlConnection(myconnection))
                {
                    con.Open();
                    SqlCommand sqlCmd = new SqlCommand();
                    sqlCmd.CommandType = CommandType.Text;
                    sqlCmd.CommandText = @"insert into dbo.feestable (feeid,Regno,Tuitionfees,Transportfees,Stationaryfees,Securityfees,Admissionfees,Others,Total) values ('" + fee.feeid + @"','" + fee.Regno + @"','" + fee.Tuitionfees + @"','" + fee.Transportfees + @"','" + fee.Stationaryfees + @"','" + fee.Securityfees + @"','" + fee.Admissionfees + @"','" + fee.Others + @"','" + fee.Total + @"')";
                    sqlCmd.Connection = con;
                    SqlDataAdapter da = new SqlDataAdapter(sqlCmd);
                    da.Fill(table);
                    
                }
                

                response = Request.CreateResponse(HttpStatusCode.OK);
                response.Content = new StringContent("Inserted Successfully", Encoding.UTF8, "application/json");
                return response;
            }
            catch (Exception ex)
            {
                response = Request.CreateResponse(HttpStatusCode.ExpectationFailed);
                response.Content = new StringContent(ex.Message, Encoding.UTF8, "application/json");
                return response;
            }

        }

我想要一个简单的错误消息,如 “ID 已存在” 和我想在前端显示的一样,但不给那个特定的异常。它不应该在控制台中给出任何错误响应。谁能帮帮我?

【问题讨论】:

  • 可以使用sql server MERGE

标签: c# exception ado.net


【解决方案1】:

我建议您查看ExecuteNonQuery - 返回您的查询更新/删除/插入的行数。

这个想法是更新 SQL 命令以仅在没有提供 feeid 的记录时执行。

SqlCommand sqlCmd = new SqlCommand();
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = @"
    IF NOT EXISTS (SELECT 1 FROM dbo.feestable WHERE feeid = " + fee.feeid + ") 
    BEGIN
        insert into dbo.feestable (feeid...
    END";
sqlCmd.Connection = con;
var res = sqlCmd.ExecuteNonQuery();
if (res > 0) {
// inserted successfully
}
else {
// record already exists
}

另外,请查看在查询中使用 SQL 参数以避免 SQL 注入。 这里有一些例子:https://docs.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlcommand

【讨论】:

  • 好的,但我认为这是程序 Sql 查询。那么我是否需要首先在我的数据库中创建这种类型的过程?或者它会按原样工作。
  • 刚刚在本地测试过,似乎工作正常,不需要存储过程。
  • 谢谢它的工作
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多