Kevin
Kevin

Reputation: 44

How to force a HTTP error in ASP.NET?

IDE: Visual Studio 2013 Ultimate
Language: C# ASP.NET webpage (aspx)
Problem: Hi! I have an assignment for school and I am making a website using ASP.NET (C#) and I need to have 3 custom errors added. I know how to force a 404 error (page not found) and a 500 error (error in code behind of the page) but I need a 3rd one and I don't know what ones I can force.

In my navigation menu I have a href to "404page.aspx" but that one doesn't exist in my solution so I get the 404 error.
In the menu I also have a href to "500error.aspx" and there I have wrong code in the code behind ("500error.aspx.cs") so I get the 500 error.

Web.Config file:

<customErrors mode="On" defaultRedirect="Error.aspx">
  <error statusCode="404" redirect="Error.aspx?error=404"/>
  <error statusCode="500" redirect="Error.aspx?error=500"/>
  <error statusCode="x" redirect="Error.aspx?error=x"/>
</customErrors>

Error.aspx.cs (code behind Error.aspx) file:

protected void Page_Load(object sender, EventArgs e)
    {
        LabelResult.Text = "";
            String errorcode = Request.QueryString.Get("error"); 
            if (errorcode.ToString().Equals("404"))
            {
                LabelResult.Text = "Page contains a 404 error.";
            }
            if (foutcode.ToString().Equals("500"))
            {
                LabelResult.Text = "Page contains a 500 error.";
            }

    }

So basically I need a 3rd HTTP error that I can force using C# or ASP.NET.

Upvotes: 2

Views: 4278

Answers (1)

DavidG
DavidG

Reputation: 118937

You either need to access a page you do not have permission to see or manually throw your own error in code behind:

throw new HttpException(403, "Access denied");

Upvotes: 5

Related Questions