如何在数据库中保存HTML内容

时间:2011-10-13 19:20:12

标签: c# asp.net sql-server asp.net-mvc razor

我的页面上有文字区域。在那个区域,我必须添加一些HTML代码并将其保存到数据库中。它适用于简单的html,但是当我从“维基百科”中选择一些文本并粘贴它并尝试在需要执行SQL查询时保存我遇到以下错误的异常:

Incorrect syntax near 's'.
The identifier that starts with '. Interestingly, old maps show the name as&nbsp;<em>Krakow</em>.</p>
<p>Kragujevac experienced a lot of historical turbulence, ' is too long. Maximum length is 128.
The identifier that starts with '>Paleolithic</a>&nbsp;era. Kragujevac was first mentioned in the medieval period as related to the public square built in a sett' is too long. Maximum length is 128.
The label 'http' has already been declared. Label names must be unique within a query batch or stored procedure.
The label 'http' has already been declared. Label names must be unique within a query batch or stored procedure.
Unclosed quotation mark after the character string '>Belgrade Pashaluk</a>.</p>'

我正在使用asp mvc和razor引擎。我不知道也许我需要以某种方式填写HTML。我还为ArticleText属性添加了这个:

[AllowHtml]        
        public string ArticleText { get; set; }

这是保存到数据库的代码:

string sql = @"insert into tbl_articles 
                               (Text) values 
                               ("'" + article.ArticleText"'"+")";

                SqlCommand cmd = new SqlCommand(sql, conn);

                cmd.ExecuteNonQuery();

5 个答案:

答案 0 :(得分:30)

哇, NO,NO,NO 。您的代码容易受到SQL注入攻击,如果您不使用参数化查询,则会发生非常糟糕的事情。所以使用参数化查询。

using (var conn = new SqlConnection("some conn string"))
using (var cmd = conn.CreateCommand())
{
    conn.Open();
    cmd.CommandText = "insert into tbl_articles (Text) values (@Text)";
    cmd.Parameters.AddWithValue("@Text", article.ArticleText);
    cmd.ExecuteNonQuery();
}

每次使用+运算符在构建SQL查询时连接字符串时,您都会做一些非常危险和错误的事情。

答案 1 :(得分:2)

尝试以这种方式保存:

string sqlQuery = "INSERT INTO tbl_articles (Text) VALUES (@text)";
SqlCommand cmd = new SqlCommand(sqlQuery, db.Connection);
cmd.Parameters.Add("@text", article.ArticleText);
cmd.ExecuteNonQuery();

答案 2 :(得分:1)

这是将系统打开为Sql injection attack的典型示例。

您需要转义'字符,因为如果Html包含'字符,它将在执行时中断SQL语句。

编辑:使用Darins解决方案来解决问题。

答案 3 :(得分:1)

尝试:

string sql = @"insert into tbl_articles 
                               (Text) values 
                               (@articleText)";

                SqlCommand cmd = new SqlCommand(sql, conn);
                cmd.Parameters.AddWithValue("@articleText",
                Server.HtmlEncode(article.articleText));

                cmd.ExecuteNonQuery();

答案 4 :(得分:1)

这应该参数化:

    public void foo(string connectionString, string textToSave)
    {
        var cmdString = "insert into tbl_articles (text) values (@text)";
        using (SqlConnection conn = new SqlConnection(connectionString))
        {
            using (SqlCommand comm = new SqlCommand(cmdString, conn))
            {
                comm.Parameters.Add("@text", SqlDbType.VarChar, -1).Value = textToSave;
                comm.ExecuteNonQuery();
            }
        }
    }

(这是一般性的想法,它不像写的那样完全有用。)