0

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

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 方法来转义由富文本编辑器创建的 html,但它不起作用。任何人都可以向我解释我要去哪里错了吗?

我收到以下服务器错误:System.Web.HttpRequestValidationException:从客户端检测到潜在危险的 Request.Form 值(ftbContent="

谢谢。

4

3 回答 3

0

尝试 HtmlEncode 和 HtmlDecode

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

于 2013-05-22T09:51:06.327 回答
0

你需要启用这个

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

in web.config:



<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0"/>
    <httpRuntime requestValidationMode="2.0"/>
  </system.web>
</configuration>

并在 Page 指令中:

ValidateRequest = "false"

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" ValidateRequest="false" %> 
于 2013-05-22T09:51:40.170 回答
0

试试这个代码:

HttpUtility.HtmlDecode(content);

注意:当您从数据库加载内容时,通过这项工作,您的文本不会以任何格式作为字符串序列

于 2013-05-22T11:01:21.233 回答