如何处理 Asp.net Web API 中的重复记录

How to handle duplicate records in Asp.net Web API

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

[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 已经存在" 和我想在前端显示的相同。它不应该在控制台中给出任何错误响应。有人可以帮我吗?

我建议您查看 ExecuteNonQuery - 您的查询 returns 行数 updated/deleted/inserted。

想法是将 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