random .NET and web development musings

This is the 2nd part to my OpenRasta introduction (see part 1 here) in which I’m going to cover Handlers and OperationResults.

Handlers are very much like MVC Controllers, except that there is no base class or interface to implement 😀 This makes them incredibly lightweight and a dream to work with.

The OpenRasta equivalent of MVC Actions are Operations. These look very similar to their MVC counterparts except we return an OperationResult instead of an ActionResult.

OperationResults represent HTTP Status codes, and you should strongly consider the choice of OperationResult that you use.

public class FooHandler
{
    private readonly IFooService fooService;

    public FooHandler(IFooService fooService)
    {
        this.fooSerivce = fooService;
    }

    public OperationResult Get(int id)
    {
        var foo = fooService.Get(id);

        if(foo == null)
            return new OperationResult.NotFound();

        return new OperationResult.OK(foo);
    }
}

(similarly to my last post, I’ll ignore the fact that we shouldn’t be sending domain objects out of our handlers for brevity of the example)

In the above case, if the IFooService cannot find the request Foo object, we return an OperationResult.NotFound which is a direct representation of HTTP Status 404.

If it is found, we return an OK (HTTP 200) passing the Foo “resource” out as the ResourceResponse for encoding later in the pipeline.

OpenRasta code is designed with discoverability in mind, intellisense is your friend. Start typing:

new OperationResult.

and see the complete list of HTTP Statuses you can return. Different results have different arguments, for example:

new OperationResult.SeeOther {RedirectLocation = "~/somewhere" }

In OpenRasta, Operations have the name of the HTTP Verb you want them to respond to (you can override this behaviour with named operations, more on this later).

This means that you have a Handler per Resource, which is an excellent means of helping enforce S.R.P.

The last part we need is the registration.

ResourceSpace.Has.ResourcesOfType<Foo>()
    .AtUri("/foo/{id}")
    .HandledBy<FooHandler>()
    .RenderedByAspx("~/Views/Foo.aspx");

The brilliant fluent configuration API makes the above code very self explanitory, but just to clarify:

ResourceSpace.Has.ResourcesOfType<Foo>() // Tell OpenRasta about our Foo type
    .AtUri("/foo/{id}") // Providing the URI where Foos reside. The brackets are parameter templating just like MVC
    .HandledBy<FooHandler>() // Here we tell OpenRasta which class handles requests for Foos
    .RenderedByAspx("~/Views/Foo.aspx"); // Here we set a WebForms codec, using the given view

How much simpler could this be?

Next post we’ll look at Pipeline Contributors

NO COMMENTS
Post a comment