views:

61

answers:

3

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?

+1  A: 

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

João Angelo
And the reason for the downvote is...
João Angelo
Are you sure this works? Have you checked the header? EDIT: seems you might be right: http://stackoverflow.com/questions/3288797/page-not-rendered-when-sending-statuscode-500-to-the-client however this is still redirection.
Codesleuth
@Codesleuth, indeed, this will depend on redirection. Also thanks for the link, I wasn't aware of that particular detail for IIS7.
João Angelo
How to use this IHttpHandler in my code? What should be the context parameter I should input? Sorry I am new to this.
Raze2dust
Solved it with some help from your post (see my own answer).. thx..
Raze2dust
Might as well delete my incorrect answer, since this works. Also, thanks! I'll be changing my old code to use this :)
Codesleuth
+2  A: 

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");
    }
Chris Diver
A: 

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!

Raze2dust
Which is identical what I said an hour ago. Glad you have fixed it :)
Chris Diver
Yea but I didn't want to create a new redirection page and I had no idea about responses one hour back. :D
Raze2dust