ServiceStack默认格式格式、ServiceStack

2023-09-03 09:59:11 作者:預約幕後︶

我想设置ServiceStack的默认格式为JSON,相对于HTML格式的响应当服务从浏览器访问它正常返回。我知道这对每个请求通过发送?格式= json的参数或接受头设置为应用程序/ JSON指定。有没有办法来改变这种无需依赖这些提示的要求?

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?

推荐答案

在除了与?格式= JSON 的通过附加格式 .EXT 的路线,比如年底:的 / rockstars.json ,或通过指定的HTTP标头(在你的HttpClient):接受:应用/ JSON

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.

否则,如果你的HttpClient不发送和接收报头,您可以指定JSON作为您的APPHOST具有默认的内容类型:

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

在ServiceStack所有配置选项都在这里设置。

All Configuration options in ServiceStack are set here.

从Web浏览器调用Web服务时的问题是,它们通常要求接受:text / html的,而不是JSON其通过合同ServiceStack责成通过返回回来的HTML,如果它被启用。

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.

要确保JSON返回您可能还需要与禁用HTML功能:

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

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

不同的方式来指定响应内容类型

否则,如果要覆盖Accept头,你可以强制服务始终返回JSON与任何一种方式来的自定义HTTP响应,例如:

使用滤波器(的AddHeader是内置的):

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