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);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…