-
Notifications
You must be signed in to change notification settings - Fork 1
Implementing a Handler
Handlers are the objects that receive requests and are responsible for returning the Resource object that will be rendered by a Codec.
OpenRasta supports POCO handlers, which means you don’t have to derive from a base class or implement any interfaces.
Let’s take the handler from the Building Your First OpenRasta Website tutorial.
public class HomeHandler
{
public object Get()
{
return new Home { Title = "Welcome home." };
}
}
You’ll notice the return type is
object
. You can go ahead and change the handler to return Home
instead. Truth be told, OpenRasta doesn’t care.
Whenever you return a resource object, OpenRasta will take the closest codec registration it can find based on media type for that registered resource type. The HTTP status code of a handler method which returns a resource object directly will ’’’always’’’ be a 200. However, we can also change the HTTP status code to whatever we want, as we’ll now see.
There are many cases where you’ll want to control the response status code. To do so, simply return an OperationResult
from your handler method. OperationResult
itself has a number of named nested classes such as OperationResult.OK
we can use to send a normal HTTP response code, and it wraps the resource we want to return. Here’s how we use it:
public OperationResult GetArticles()
{
return new OperationResult.OK { ResponseResource = new Article() };
}
Notice that we set the
OperationResult.ResponseResource
to the resource we want to return.
Handlers can also return void
.
public void Post() {}
In this case, a 204 – “No Content” result will be returned to the client.
We might have written a handler which gets an article by its ID. Such a method might look like this:
public class ArticleHandler
{
public Article GetById(int id)
{
return ArticleRepository.GetById(id);
}
}
OpenRasta will ensure that this method is called provided we registered the handler against an appropriate URI template that matches the method signature on the handler. For example:
ResourceSpace.Has.ResourcesOfType<Article>()
.AtUri("/articles/{id}")
.HandledBy<ArticleHandler>()
// Representations go here
Here we can see that /articles/{id}
is a URI which has one parameterizable part, and hence our ArticleHandler.GetById(int)
will be considered as a candidate method. For a fuller discussion of handler method selection, see Handler Method Selection.