如何将richtext编辑器中的内容输入到c#中的数据库?

如何将richtext编辑器中的内容输入到c#中的数据库?,c#,asp.net,.net,sql,content-management-system,C#,Asp.net,.net,Sql,Content Management System,我正在尝试建立一个简单的CMS作为一个项目来帮助我学习和提高我的asp.net和c#技能。我已经设置了我的web表单,正在使用以下代码将内容输入数据库: protected void btnSave_Click(object sender, EventArgs e) { //Set up connection string. const string connectionString = "Data Source=localhost;Initial Cat

我正在尝试建立一个简单的CMS作为一个项目来帮助我学习和提高我的asp.net和c#技能。我已经设置了我的web表单,正在使用以下代码将内容输入数据库:

protected void btnSave_Click(object sender, EventArgs e)
    {
        //Set up connection string.
        const string connectionString = "Data Source=localhost;Initial Catalog=CMSDatabase;Integrated Security=True";

        //SQL statement
        string statement = "INSERT INTO PageContent(Title, Content, Image) VALUES (@title, @content, @image)";
        SqlCommand command = new SqlCommand(statement);

        //Escape special characters
        string content = Regex.Escape(ftbContent.Text);

        //Add contents of form to the database.
        command.Parameters.AddWithValue("@title", txtTitle.Text);
        command.Parameters.AddWithValue("@content", content);
        command.Parameters.AddWithValue("@image", txtImage.Text);

        try
        {
            SqlConnection connection = new SqlConnection(connectionString);
            connection.Open();
            command.Connection = connection;
            command.ExecuteNonQuery();
        }
        catch
        {
            //do exception handling stuff
        }
    }
我曾尝试使用Regex.Escape方法来转义richtext编辑器创建的html,但它不起作用。谁能告诉我哪里出了问题吗

我收到以下服务器错误: System.Web.HttpRequestValidationException:潜在危险的请求。从客户端检测到表单值(ftbContent=”
谢谢。

试试HtmlEncode和HtmlDecode

字符串内容=Server.HtmlEncode(ftbContent.Text)


您需要启用此功能

我们只需在Web.config文件中添加一行代码,在Default.aspx表单(带有富文本编辑器的页面)中添加一个属性。 即:

in web.config:



<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0"/>
    <httpRuntime requestValidationMode="2.0"/>
  </system.web>
</configuration>
web.config中的
在第页指令中:

ValidateRequest = "false"

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" ValidateRequest="false" %> 
ValidateRequest=“false”
尝试以下代码:

HttpUtility.HtmlDecode(content);

注意:通过这项工作,无论何时从数据库加载内容,您的文本都不会以字符串序列的形式出现。

执行RegEx.ftbContent后,您可以告诉我示例值内容吗。文本应该只有文本,不会是任何html思维。这是什么问题?您是否收到错误消息?尝试推送html con通过请求可能会导致请求验证失败。@Bartdude Yes我收到一个服务器错误,上面写着:System.Web.HttpRequestValidationException:一个潜在的危险请求。从客户端检测到表单值(ftbContent=)问题是文本属性有HTml标记,一旦启用此功能,您可以将数据发送到服务器,但要小心,并且只能在用户应该输入HTml内容的页面上停用请求验证。请注意,这并不能免除您使用htmlencode/htmldecode的权限,请检查是否存在最终的恶意代码或使用不需要的代码html标记向我展示你的html,它一直对我有效,让我们看看为什么它对你无效。