c# - 如何修复此错误以防止返回“测验”页面并更改他的答案?

标签 c# asp.net

我现在正在开发的 Web 应用程序有一个叫做测验引擎的东西,它为用户提供由一个或多个问题组成的简短测验。现在,我在参加/回答测验时遇到了问题: 当用户完成由 4 个问题组成的测验并转到结果页面时,他可以返回(使用浏览器中的后退箭头)到测验页面并再次回答任何问题,这不应该发生,我也不会不知道如何预防

为了创建测验引擎,我使用了 ASP.NET 网站中测验引擎的 Toturial 来创建我所拥有的。

ASP.NET 代码:

<tr>
                <td>
                    <asp:DetailsView ID="questionDetails" runat="server" Height="50px" Width="550px" AutoGenerateRows="False" CellPadding="4" DataSourceID="SqlDataSource1" ForeColor="#333333" GridLines="None">
                        <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                        <CommandRowStyle BackColor="#E2DED6" Font-Bold="True" />
                        <RowStyle BackColor="#F7F6F3" ForeColor="#333333" CssClass="generaltext" />
                        <FieldHeaderStyle BackColor="#E9ECF1" Font-Bold="True" CssClass="boldtext" Width="80px" />
                        <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
                        <Fields>
                            <asp:BoundField DataField="Question" HeaderText="Question:" SortExpression="Question" />
                            <asp:BoundField DataField="Answer1" HeaderText="A:" SortExpression="Answer1" />
                            <asp:BoundField DataField="Answer2" HeaderText="B:" SortExpression="Answer2" />
                            <asp:BoundField DataField="Answer3" HeaderText="C:" SortExpression="Answer3" />
                            <asp:BoundField DataField="Answer4" HeaderText="D:" SortExpression="Answer4" />
                        </Fields>
                        <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                        <EditRowStyle BackColor="#999999" />
                        <AlternatingRowStyle BackColor="White" ForeColor="#284775" CssClass="generaltext" />
                    </asp:DetailsView>
                    &nbsp;
                    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:testConnectionString %>" SelectCommand="SELECT [QuestionID], [Question], [Answer1], [Answer2], [Answer3], [Answer4], [CorrectAnswer], [QuestionOrder] FROM [Question] WHERE ([QuizID] = @QuizID) ORDER BY [QuestionOrder]">
                        <SelectParameters>
                            <asp:SessionParameter SessionField="QuizID" Type="Int32" Name="QuizID" DefaultValue="0" />
                        </SelectParameters>
                    </asp:SqlDataSource>
                </td>
            </tr>

            <%--<tr>
                <td>&nbsp;
                </td>
            </tr>--%>

            <tr>
                <td class="boldtext">
                    <strong>Your Answer:</strong>&nbsp;
                <asp:DropDownList ID="answerDropDownList" runat="server">
                            <asp:ListItem Value="A">A</asp:ListItem>
                            <asp:ListItem Value="B">B</asp:ListItem>
                            <asp:ListItem Value="C">C</asp:ListItem>
                            <asp:ListItem Value="D">D</asp:ListItem>
                        </asp:DropDownList>
                </td>
            </tr>

我的代码隐藏:

这是负责保存答案的代码:

protected void Page_Load(object sender, EventArgs e)
    {

        questionDetails.DataBind();

        answerDropDownList.SelectedIndex = 0;

        if (questionDetails.PageCount == 1)
        {
            nextButton.Text = "Finished";
        } 
    }

    protected void nextButton_Click(object sender, EventArgs e)
    {
        // Save off previous answers
        System.Data.DataRowView dr = (System.Data.DataRowView)questionDetails.DataItem;

        // Create Answer object to save values
        Answer a = new Answer();
        a.QuestionID = dr["QuestionOrder"].ToString();
        a.CorrectAnswer = dr["CorrectAnswer"].ToString();
        a.UserAnswer = answerDropDownList.SelectedValue.ToString();

        ArrayList al = (ArrayList)Session["AnswerList"];

        var oldAnswer = al.ToArray().Where(ans => (ans as Answer).QuestionID == a.QuestionID);
        if (oldAnswer.Count() != 0)
        {
            a = oldAnswer.FirstOrDefault() as Answer;
            a.CorrectAnswer = dr["CorrectAnswer"].ToString();
            a.UserAnswer = answerDropDownList.SelectedValue.ToString();
        }
        else
        {
            al.Add(a);
        }


        if (questionDetails.PageIndex == questionDetails.PageCount - 1)
        {
            // Go to evaluate answers
            Response.Redirect("Results.aspx");
        }
        else
        {
            questionDetails.PageIndex++;
        }

        if (questionDetails.PageIndex == questionDetails.PageCount - 1)
        {
            nextButton.Text = "Finished";
        }

    }

下面的代码负责保存结果:

protected void Page_Load(object sender, EventArgs e)
    {
        ArrayList al = (ArrayList)Session["AnswerList"];

        if (al == null)
        {
            Response.Redirect("default.aspx");
        }

        resultGrid.DataSource = al;
        resultGrid.DataBind();

        // Save the results into the database.
        if (IsPostBack == false)
        {
            // Calculate score
            double questions = al.Count;
            double correct = 0.0;


            for (int i = 0; i < al.Count; i++)
            {
                Answer a = (Answer)al[i];
                if (a.Result == Answer.ResultValue.Correct)
                    correct++;
            }

            double score = (correct / questions) * 100;
            string username = HttpContext.Current.User.Identity.Name.ToString().Replace("ARAMCO\\", "");
            SqlDataSource userQuizDataSource = new SqlDataSource();
            userQuizDataSource.ConnectionString = ConfigurationManager.ConnectionStrings["testConnectionString"].ToString();
            userQuizDataSource.InsertCommand = "INSERT INTO [UserQuiz] ([QuizID], [DateTimeComplete], [Score], [Username]) VALUES (@QuizID, @DateTimeComplete, @Score, @Username)";

            userQuizDataSource.InsertParameters.Add("QuizID", Session["QuizID"].ToString());
            userQuizDataSource.InsertParameters.Add("DateTimeComplete", DateTime.Now.ToString());

            // "N4" is for displaying four decimal places, regardless of what the value is 
            userQuizDataSource.InsertParameters.Add("Score", score.ToString("N4"));

            userQuizDataSource.InsertParameters.Add("Username", username);

            int rowsAffected = userQuizDataSource.Insert();
            if (rowsAffected == 0)
            {
                // Let's just notify that the insertion didn't
                // work, but let' s continue on ...
                errorLabel.Text = "There was a problem saving your quiz results into our database.  Therefore, the results from this quiz will not be displayed on the list on the main menu.";


            }

        }


    }


    protected void resultGrid_SelectedIndexChanged(object sender, EventArgs e)
    {
        SqlDataSource1.FilterExpression = "QuestionOrder=" + resultGrid.SelectedValue;
    }

那么现在我怎样才能阻止用户在结果页面中返回测验呢?

最佳答案

您可以使用 Response.Cache 属性来解决这个问题。 来自 MSDN Response. SetAllowResponseInBrowserHistory

When HttpCacheability is set to NoCache or ServerAndNoCache the Expires HTTP header is by default set to -1; this tells the client not to cache responses in the History folder, so that when you use the back/forward buttons the client requests a new version of the response each time. You can override this behavior by calling the SetAllowResponseInBrowserHistory method with the allow parameter set to true.

在您的页面加载方法中,添加这一行。

 protected void Page_Load(object sender, EventArgs e)
  {
       Response.Cache.SetCacheability(HttpCacheability.NoCache); 
       Response.Cache.SetAllowResponseInBrowserHistory(false);

        // or else you can do like this 

       Response.ExpiresAbsolute = DateTime.Now.AddDays(-1d);
        Response.Expires = -1;
        Response.CacheControl = "No-cache";
  }

关于c# - 如何修复此错误以防止返回“测验”页面并更改他的答案?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9059803/

相关文章:

c# - 理解C#的类型转换

c# - 找不到方法 : 'System.Net.Http.Headers.MediaTypeHeaderValue System.Net.Http.Formatting.JsonMediaTypeFormatter.get_DefaultMediaType()'

asp.net - ASP 5 MVC 6 - 优点和缺点 : multiple web api services - use one or more projects?

asp.net - 获取 ASP.NET 表单名称

c# - 类/模型级别验证(相对于属性级别)? (ASP.NET MVC 2.0)

c# - System.Net.PeerToPeer 是否已从 .NET 4.5 中删除? C#

c# - 使用特殊字符时出现解析错误

c# - 显示希伯来语 sqlplus

c# - 未针对 CompositeCollection 和嵌套 CollectionViewSource.Source 绑定(bind)正确引发依赖项 PropertyChangedHandler

asp.net - AntiForgery Token 使用 ASP.NET5 Web API,在 NET46 上没有 System.Web.Helpers