ServiceStack default format

Jarrod picture Jarrod · Apr 25, 2012 · Viewed 8k times · Source

I would like to set ServiceStack's default format to JSON, as opposed to the HTML formatted response it normally returns when a service is accessed from a browser. I know this can be specified on each request by sending a ?format=json parameter or setting the Accept header to application/json. Is there a way to change this without having to rely on these hints from the request?

Answer

mythz picture mythz · Apr 25, 2012

In addition to specifying it on the QueryString with ?format=json, by appending the format .ext to the end of the route, e.g: /rockstars.json, or by specifying the HTTP Header (in your HttpClient): Accept: application/json.

Otherwise if your HttpClient doesn't send an Accept header you can specify JSON as the default content type in your AppHost with:

SetConfig(new HostConfig {
     DefaultContentType = MimeTypes.Json 
});

All Configuration options in ServiceStack are set here.

The issue when calling web services from a web browser is that they typically ask for Accept: text/html and not JSON which by contract ServiceStack obliges by returning back HTML if it is enabled.

To ensure JSON is returned you may also want to disable the HTML feature with:

SetConfig(new HostConfig {
    EnableFeatures = Feature.All.Remove(Feature.Html),
});

Different ways to specify the Response Content Type

Otherwise if you want to override the Accept header you can force your service to always return json with any of these ways to Customize the HTTP Response, e.g:

Using a filter (AddHeader is built-in):

[AddHeader(ContentType=MimeTypes.Json)]
public object Any(Request request) { ... }

Setting the Response in the service:

public object Any(Request request) 
{ 
    base.Response.ContentType = MimeTypes.Json;
    return dto;
}

Returning a decorated response:

return new HttpResult(dto, MimeTypes.Json);