Controllers in Wisp are classes that handle incoming HTTP requests and return responses in the form of views, JSON, or other data.
They are inspired by the familiar ASP.NET MVC model but are much lighter and easier to embed in small projects.
To define a controller, create a class and annotate it with the [Controller]
attribute.
Controller methods can then be annotated with [Route]
to define how requests map to methods.
Extending ControllerBase
is not mandatory, but it provides convenience functions such as View
and Redirect
. Without
these, you will need to construct views yourself (e.g. new TemplateView("demo")
).
using Wisp.Framework.Controllers;
using Wisp.Framework.Views;
[Controller]
public class HomeController : ControllerBase
{
[Route("/")]
public async Task<IView> Index()
{
return View("home");
}
[Route("/about")]
public async Task<IView> About()
{
return View("about");
}
}
[Route("path")]
./about
) or parameterized (e.g., /products/{id}
).Example of route with parameters:
[Route("/products/{id}")]
public async Task<IView> Product(IHttpRequest req)
{
var id = req.PathVars["id"];
var model = ProductRepository.Get(id);
return new TemplateView("product", model);
}
Path parameters are automatically passed into method parameters if names match.
Controller methods return something implementing IView
.
The framework includes TemplateView
for rendering .liquid
templates, but you can create your own.
[Route("/")]
public async Task<IView> Index()
{
// The View Model can be an anonymous object
return View("home", new { Message = 'Hello, Wisp!' });
}
[Route("/go-home")]
public async Task<IView> RedirectHome()
{
return Redirect("/");
}
Controllers keep your application organized: