如何使用c#编辑.aspx页面并保存在asp.net上点击按钮?

时间:2012-12-18 12:06:36

标签: c# asp.net writetofile textwriter

我是一个.aspx页面列表,它位于DropdownList中,来自应用程序根目录。我在RichTextBox中显示整个.aspx页面内容以进行编辑。但是,当我单击“保存”按钮时,它显示错误:从客户端检测到一个潜在危险的Request.Form值(ctl00 $ MainContent $ TextBox1 =“... xt”%>

示例代码:

<asp:TextBox ID="TextBox1" runat="server" Height="314px" TextMode="MultiLine" 
        Width="771px"></asp:TextBox>

<asp:Button ID="BtnSaveContent" runat="server" onclick="BtnSaveContent_Click" 
        Text="Save Content" />

In .aspx.cs file:
private void GetFilesNames()
    {


        TextReader tr = new StreamReader(Server.MapPath("") + "/CopyText.aspx");
        TextBox1.Text = tr.ReadToEnd();
        // close the stream
        tr.Close();
    }


    protected void BtnSaveContent_Click(object sender, EventArgs e)
    {
        WritetoFile();
    }

    private void WritetoFile()
    {
        TextWriter tw = new StreamWriter(Server.MapPath("") + "/CopyText.aspx");

        // write a line of text to the file
        tw.WriteLine(TextBox1.Text);

        // close the stream
        tw.Close();
    }

页面标题:

<%@ Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" validateRequest="false" CodeFile="CopyText.aspx.cs" Inherits="CopyText" %>

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" validateRequest = false
    CodeFile="Default.aspx.cs" Inherits="_Default" %>

我还在页面级别和控制级别尝试了validateRequest =“false”。但不起作用! 有什么想法来解决这个错误吗? 帮助赞赏!

1 个答案:

答案 0 :(得分:0)

你说得对,你需要validateRequest = false

但如果这是.Net 4.0,您还需要将requestValidationMode="2.0"添加到web.config的httpRuntime配置部分:

<system.web>
  <httpRuntime requestValidationMode="2.0"/>
</system.web>