c# - 检查两个值的空字符串或空字符串 C#
问题描述
我想检查主题代码和主题名称的空字符串或空值,以便主题代码和主题名称的空字符串不会存储在数据库中。我是 C# 的新手。代码有错误。它声明不能从布尔转换为字符串。我尝试了很多方法,但错误仍然存在。在修复了从 bool 转换为 string 的错误后,它返回了一个Not Found
错误。我应该如何更改return NotFound()
错误?
public IHttpActionResult PostAddSubjectCode([FromBody] ConfigSubjectCode SubjectCodes)
{
string Subject_Code = SubjectCodes.Subject_Code;
string Subject_Name = SubjectCodes.Subject_Name;
if (String.IsNullOrEmpty(Subject_Code) && String.IsNullOrEmpty(Subject_Name))
{
return NotFound();
}
else
{
string sql = "INSERT INTO[dbo].[GEO_SUBJECT_CODES] ([Subject_Code],[Subject_Name_BY_CLASS]) VALUES " +
"('" + Subject_Code + "', '" + Subject_Name + "');";
DBConnection dbConnection = new DBConnection();
dBConnection.UpdateTable(sql);
return Ok();
}
}
解决方案
该错误准确地说明了问题所在:您将
boolean
(Subject_Code == "" && Subject_Name == ""
) 传递给String.IsNullOrEmpty
期望string
您正在为要检查的变量设置空字符串,使
if
检查毫无意义您的 SQL 对注入开放
强烈建议:ASP.NET MVC 5 入门,它也将链接到较新的Core
示例。
我会在这里保留这个,因为我们有一个线程来指出列出的问题。
// These will make the if statement useless, it will never hit else
// string Subject_Code = "";
// string Subject_Name = "";
//Assumptions: Subject_Codes contians these props
if(string.IsNullOrEmtpy(SubjectCodes.Subject_Code) && string.IsNullOrEmpty(SubjectCodes.Subject_Name)){
// whatever you want to do...
} else {
//sql here - I'll skip the comments on why your sql is bad - re: use parameters
// return after successful sql - look into a try/catch
}
在您的模型中查看DataAnnotations [必需] - 您将获得服务器和客户端验证。我强烈建议你阅读大量的教程而不是零碎的东西。
推荐阅读
- java - Spring JPA PESSIMISTIC_WRITE 锁定模式在其他事务读取同一行时不锁定行
- rxjs - 用嵌套数组链接 rxjs 6 个 observables
- javascript - React hook Search on button click 不起作用
- django - 预期视图功能的Django url单元测试比较失败
- asp.net-core - 503 服务不可用的 Asp Net Core 3 示例
- android - How do I pass a filename parameter to MediaPlayer in android kotlin?
- outlook-addin - 在 Outlook 365 上呈现复杂的 div
- c++ - 为什么 GTK 按钮会产生:“进程以退出代码 139 完成(被信号 11 中断:SIGSEGV)”?
- java - 是否可以使用 SnakeYaml 写评论?
- azure - Azure AD Graph API - 一次性获得组成员资格