【问题标题】:Cannot return json object as string无法将 json 对象作为字符串返回
【发布时间】:2015-10-24 13:27:03
【问题描述】:

我有一个返回字符串数据类型的 C# 函数。我想将 json 对象作为字符串返回,但出现此错误: CS1002: ;预期的 这是函数:

    public String LoginUser(string Username, string Password)
   {
               string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
               SqlConnection con = new SqlConnection(constr);
               try
               {
                   SqlCommand cmd = new SqlCommand("Login_User");
                   cmd.CommandType = CommandType.StoredProcedure;
                   cmd.Parameters.AddWithValue("@Username", Username);
                   cmd.Parameters.AddWithValue("@Password", Password);
                   cmd.Connection = con;
                   if (con.State == ConnectionState.Closed)
                   {
                       con.Open();
                   }
                   SqlDataReader rd = cmd.ExecuteReader();
                   if (rd.HasRows)
                   {
                       rd.Read();
                       return "{"message": "Successfully"}"; //me sukses
                   }

                   else
                       return "{"message": "Invalid Username and/or Password"}"; //pas sukses
               }

               catch (Exception ex)
               {
                   throw ex;
               }
               finally
               {
                   if (con.State != ConnectionState.Closed)
                   {
                       con.Close();
                   }
               }
  }

【问题讨论】:

    标签: c# json c#-4.0


    【解决方案1】:

    据我所知,两个字符串都需要escape " character

    return "{\"message\": \"Successfully\"}"; //me sukses
    

    return "{\"message\": \"Invalid Username and/or Password\"}";
    

    或者使用逐字字符串文字,就像将它们加倍一样;

    return @"{""message"": ""Invalid Username and/or Password""}";
    

    return "{""message"": ""Invalid Username and/or Password""}";
    

    使用using statement 自动处理您的连接、命令和阅读器,而不是手动调用CloseDispose 方法。

    不要使用AddWithValue 方法。 It may generate unexpected and surprising results sometimes。使用Add 方法重载来指定你的参数类型和它的大小。

    但我强烈怀疑您将密码保存为纯文本的方式。 不要这样做。阅读Best way to store password in database

    【讨论】:

    • 但是当我使用 JQuery 使用此方法时,浏览器中的响应格式显示为斜杠 / 。当在浏览器中返回时,我想从对象中删除斜杠!!!我该怎么做?
    • 我想返回不带 \ 的结果。当在浏览器中返回时,我想从对象中删除所有 / !!!我该怎么做?
    【解决方案2】:

    在字符串前使用@ 可以轻松地转义双引号。

    return @"{"message": "Invalid Username and/or Password"}";
    

    尝试改变:

               catch (Exception ex)
               {
                      throw ex;  // don't do this
               }
    

    收件人:

               catch (SqlException ex)
               {
                   return string.Format("error: {0}", ex.message);
               }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-02
      • 1970-01-01
      相关资源
      最近更新 更多