Skip to content

Service return types

IcodeNet edited this page Sep 4, 2012 · 5 revisions

From a birds-eye view ServiceStack can return any of:

  • Any DTO object -> serialized to Response ContentType
  • HttpResult, HttpError, CompressedResult (IHttpResult) for Customized HTTP response
public class HelloService : RestServiceBase<Hello>
{ 
    public  override object OnGet(Hello request) 
    { 
        var responseDto;
        return new HttpResult(responseDto, HttpStatusCode.Conflict);

        //or with HttpError:
        return new HttpError(System.Net.HttpStatusCode.Conflict, "SomeErrorCode");
    }
}

Tip: You can also throw an HttpError everywhere in your code and it will behave the same as returning the http error: throw new HttpError(System.Net.HttpStatusCode.Conflict, "SomeErrorCode");

The following types are not converted and get written directly to the Response Stream:

  • String
  • Stream
  • IStreamWriter
  • byte[] - with the application/octet-stream Content Type.
public class HelloService : RestServiceBase<Hello>
{ 
    public object override OnGet(Hello request) 
    { 
        return "Hello string";
    } 
} 

Details

In addition to returning plain C# objects, ServiceStack allows you to return any Stream or IStreamWriter (which is a bit more flexible on how you write to the response stream):

    public interface IStreamWriter
    {
        void WriteTo(Stream stream);
    }

Both though allow you to write directly to the Response OutputStream without any additional conversion overhead.

If you want to customize the HTTP headers at the sametime you just need to implement IHasOptions where any Dictionary Entry is written to the Response HttpHeaders.

    public interface IHasOptions
    {
        IDictionary<string, string> Options { get; }
    }

Further than that, the IHttpResult allows even finer-grain control of the HTTP output (status code, headers, ...) where you can supply a custom Http Response status code. You can refer to the implementation of the HttpResult object for a real-world implementation of these above interfaces.