Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Service Stack - Return HttpResult or ResponseDTO

Tags:

servicestack

I just started to use ServiceStack to implement an API samples and went through a lot of examples, some examples return HttpResult from the service and others return ResponseDTO, which one is preferred?

like image 622
J.W. Avatar asked Oct 19 '13 10:10

J.W.


1 Answers

Returning just the Response DTO is preferred which basically means you're happy with the default behavior and your service will return the response body as-is, serialized into the requested Content-Type.

The HttpResult is for when your service needs to add additional HTTP customizations in addition to the Response (e.g. additional HTTP Headers) - but it doesn't change the wire-format of the HTTP Response body (unless you change the Content-Type which will change what the response is serialized to).

Although the HttpResult is just one way to customize the Response, here are a few others:

public class HelloService : Service
{ 
    public object Get(Hello request) 
    { 
        //1. Returning a custom Response Status and Description with Response DTO body:
        var responseDto = ...;
        return new HttpResult(responseDto, HttpStatusCode.Conflict) {
            StatusDescription = "Computer says no",
        };

        //2. Throw or return a HttpError:
        throw new HttpError(System.Net.HttpStatusCode.Conflict, "SomeErrorCode");

        //3. Modify the Request's IHttpResponse
        base.Response.StatusCode = (int)HttpStatusCode.Redirect;
        base.Response.AddHeader("Location", "http://path/to/new/uri");
    }

    //4. Using a Request or Response Filter 
    [AddHeader(ContentType = "text/plain")]
    public string Get(Hello request)
    {
        return "Hello, {0}!".Fmt(request.Name);
    }
}

See the Customize HTTP Responses wiki for more info.

like image 156
mythz Avatar answered Oct 30 '22 14:10

mythz