如何确保ServiceStack始终返回JSON?

时间:2016-04-14 12:09:43

标签: json text servicestack http-error

我们决定只允许具有Content-Type标头“application / json”的请求。 因此,每当我们收到带有替代或缺少Content-Type标头的请求时,我们都会抛出一个HttpError。此应该返回包含带有相关信息的JSON ResponseStatus主体的400响应。 但是,如果发送Content-Type text / plain,我们会抛出一个HttpError,但响应的Content-Type是text / plain和content-length:0。我希望返回ServiceStack的ResponseStatus。如果我向请求添加Accept application / json标头,则ResponseStatus会正常返回。 我使用Postman执行了请求。 Fiddler4屏幕截图:

我知道Postman添加了Accept / 标头。所以我的问题是:如何确保抛出的HttpError始终将ResponseStatus作为JSON返回,无论请求的Accept头部是什么?

SetConfig:

SetConfig(new HostConfig
        {
            EnableFeatures = Feature.All.Remove( Feature.Html | Feature.Csv | Feature.Jsv | Feature.Xml | Feature.Markdown | Feature.Razor | Feature.Soap | Feature.Soap11 | Feature.Soap12 | Feature.PredefinedRoutes),
            DebugMode = false,
            DefaultContentType = MimeTypes.Json
        });

据我了解,只有在请求中没有Accept标头时才会使用DefaultContentType。

PreRequestFilter:

PreRequestFilters.Add((request, response) =>
        {
            if (request.Verb.Equals("OPTIONS"))
                response.EndRequest();
            if (request.GetHeader("Content-Type") == null || !request.GetHeader("Content-Type").Equals(MimeTypes.Json))
                throw new HttpError((int)HttpStatusCode.BadRequest, "Bad request", "Expected a Content-Type header with an application/json value but found none. See http://docsdomain.com/ for any required headers.");
        });

1 个答案:

答案 0 :(得分:2)

HTTP Accept标头是客户端用来指示应返回响应类型的标头,但您可以通过添加全局请求过滤器并显式设置ResponseContentType来覆盖此标题以始终返回JSON,例如:

GlobalRequestFilters.Add((req,res,dto) => 
    req.ResponseContentType = MimeTypes.Json);

如果Accept标题未指定特定的响应类型,则默认使用PreferredContentTypes,您可以通过以下方式更改:

SetConfig(new HostConfig {
    PreferredContentTypes = new []{ MimeTypes.Json }.ToList(),
});