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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With