Tutorial part five - Using controllers

Controllers are quite easy to use. What they do is to take advantage of the first three parts (using slash as a separator) of the url. The url http://localhost/user/view/1 tells the controller module that the controller named User or UserController should be used, and the method called "public string View()" should be called. 1 is stored in the controller property called "Id".

This allows us to write a simple method to handle that url:
public class UserController : RequestController
{
  public string View()
  {
    return "Ohh, hello!, so you want to look at user with id #" + Id + "??";
  }
}


Then you'll need to start a webserver with that controller:
ControllerModule mod = new ControllerModule();
mod.Add(new UserController());

HttpServer server = new HttpServer();
server.Add(mod);

server.Start(IPAddress.Any, 80);

Before filters

Have you ever used user authentication in your systems? Thought so. This is to simple to implement. It can be done with a before filter.
A before filter is invoked before each request method. Before filters can abort the processing (preventing the controller method to be invoked).
A common usage would be to validate user.
class UserController : RequestController
{
  [BeforeFilter]
  private bool ValidatorUser()
  {
    if (Session["userid"] == null && MethodName != "login")
    {
      Response.Redirect("/user/login");
      return false;
    }
    return true;
  }

  public string Index()
  {
    return "So you decided to login, eehh??";
  }

  public string Login()
  {
    if (Request.Method == "POST")
      //login
    else
      //show login form
  }
}


Questions?

Last edited May 9, 2008 at 1:23 PM by jgauffin, version 4

Comments

No comments yet.