Skip to content

Cormo.Web: Injecting responses #10

@hendryluk

Description

@hendryluk

Currently this is how you set response details (e.g. headers) with Cormo (or rather, WebApi):

[RestController]
public class MyController
{
    [Route, HttpGet]
    public HttpResponseMessage DoSomething()
    {
        /* ... */
        var response = Response.Ok(something);
        response.Headers.LastModified = content.LastModified;
        return response;
    }
}

That's the same way in JBoss.
But additionally, according to the CDI spec (or rather, JBoss Seam), there's an alternative way may be better for flattening your code, which is by injecting your HttpResponseMessage to components. The benefit being that setting headers can be done by any component, no longer necessarily only by your controller (or UI layer in general).
Ref: http://docs.jboss.org/seam/3/latest/reference/en-US/html_single/#injectablerefs.http_servlet_reponse
E.g.

public class MyShoppingCart
{
   [Inject] HttpResponseMessage _response;
   public void DoSomething()
   {
       /* ... */
       response.Headers.LastModified = items.LastModified;
   }
}

This will add the header to the response that's eventually returned by web-api, even though the controller code is totally oblivious to it:

[RestController]
public class MyController
{
    [Route, HttpGet]
    public string DoSomething()
    {
        /* ... */
        _cart.DoSomething();
        return something;
    }
}

This helps reducing vertical layering in your application and simplifies some code by removing some unnecessary patterns.
PS: I'll leave it to you to decide whether that's a "good practice" to mix http concerns into your components, but some components are inherently web-coupled, such as identities, security (e.g. anti-csrf), captcha, and web-analytics functionalities, which are all commonly designed as components/interceptors/decorators. CDI provides a decoupled way to wire those up without introducing noise in your controller.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions