Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
520 views
in Technique[技术] by (71.8m points)

c# - ServiceStack default format

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...