Hari Menon
Hari Menon

Reputation: 35405

How to throw HTTP errors?

I am using Response.Redirect to redirect the user to a new page but I want the page to be shown only if there is a particular parameter in the query string. Otherwise, I want an HTTP 401 authentication error page to be shown. Can that be done? If yes, how? If not, why not?

Upvotes: 4

Views: 6414

Answers (3)

Hari Menon
Hari Menon

Reputation: 35405

I think I figured out the answer myself, with some help from Joao and the answers provided by others..

I simply have to write this:

 if (Request.Params[param] != nul)
            {
               ...
            }
            else
            {
                Response.ContentType = "text/html";
                Response.Write("Authentication error");
                Response.StatusCode = 401;
                Response.End();
            }

Simple! :) Let me know if there's any potential issue with this!

Upvotes: 0

Chris Diver
Chris Diver

Reputation: 19802

The following returns a 401 status code, you will need to add the HTML to display yourself depending how IIS is configured.

    protected void Page_Load(object sender, EventArgs e)
    {
        if (String.IsNullOrEmpty(Request.QueryString["RedirectParam"]))
            Response.StatusCode = 401; 
        else
            Response.Redirect("redirectpage.html");
    }

Upvotes: 2

João Angelo
João Angelo

Reputation: 57658

From your page, you could redirect to an IHttpHandler that would output the content for your authentication error page and would set the HTTP status code to 401.

public void ProcessRequest(HttpContext context)
{
    context.Response.ContentType = "text/plain";
    context.Response.Write("Authentication error");
    context.Response.StatusCode = 401;
}

The MSDN topic for IHttpHandler as some links that may help you understand what is an HTTP handler and how you can implement one. The most important ones are:

HTTP Handlers and HTTP Modules Overview

Walkthrough: Creating a Synchronous HTTP Handler

How to: Register HTTP Handlers

Upvotes: 3

Related Questions