Simple Redirect

Topics: blog, faq
Nov 5, 2012 at 11:04 AM
Edited Nov 5, 2012 at 11:05 AM

Hi, I was playing with this great library but I quite couldn't get how to perform a simple task.

 

I have an incoming POST request, where I check some login data.

There might be two possible outcomes, all analyzed by the c# webserver: if the data is ok I send him an image, if not, i send him another image.

 

I was thinking about using the following workflow

 

    private static void Main(string[] args)
        {
            // create a server.
            HttpServer server = new Server();
            
// Create a callback
            server.RequestReceived += OnRequest;
            
            server.Add(new MultiPartDecoder());

            // use one http listener.
            server.Add(HttpListener.Create(IPAddress.Any, 8085));
// Add some routers

            // start server, can have max 5 pending accepts.
            server.Start(5);

            Console.ReadLine();
        }

private static void OnRequest(object sender, RequestEventArgs e)
        {


            if (e.Request.Method == Method.Post)
            {
                bool _stuffIsThere = false;
                IParameter username = null;
                IParameter password = null;
                try
                {
                    username = e.Request.Form.Get("username");
                    password = e.Request.Form.Get("password");
                    _stuffIsThere = true;
                }
                catch
                {
                    _stuffIsThere = false;
                }

                if (_stuffIsThere)
                {
                    if ((username != null) && (username.Value == "SomeValue")) // additional tests for password will be added
                    {
                        // Redirect to ok                        
e.Response.Connection.Type = ConnectionType.Close;
e.Context.Response.Redirect("/Images/ok.gif"); } else { // Redirect to error e.Response.Connection.Type = ConnectionType.Close; e.Response.Redirect("/Images/error.jpg"); } } } else { // do nothing } }

This is not working, although the 'Redirect' exists. What am I doing wrong?
Developer
Nov 6, 2012 at 12:15 PM

1. In the code above there's no module added to server, which could actually serve the images. The Response.Redirect(...) function will send a redirect header to the browser, which in turn will send a request for the image, so you'll need a file module to serve it.

2. As a rule of thumb: don't use the RequestReceived event. Write your own module, or in this case, a router will be perfectly fine. Just derive from IRouter (have a look at the SimpleRouter class for example) and add the router to the server (you will still need a file module).