首页 > 解决方案 > 检查两个值的空字符串或空字符串 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();
        }

        }   

标签: c#sql

解决方案


  1. 该错误准确地说明了问题所在:您将boolean( Subject_Code == "" && Subject_Name == "") 传递给String.IsNullOrEmpty期望string

  2. 您正在为要检查的变量设置空字符串,使if检查毫无意义

  3. 您的 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 [必需] - 您将获得服务器和客户端验证。我强烈建议你阅读大量的教程而不是零碎的东西。


推荐阅读