【发布时间】: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