What's the best way to respond with the correct content type from request filter in ServiceStack?

≡放荡痞女 提交于 2019-12-01 21:39:16

ServiceStack pre-calculates the Requested Content-Type on a number of factors (e.g. Accept: header, QueryString, etc) it stores this info in the httpReq.ResponseContentType property.

You can use this along with the IAppHost.ContentTypeFilters registry which stores a collection of all Registered Content-Type serializers in ServiceStack (i.e. built-in + Custom) and do something like:

var dto = ...;
var contentType = httpReq.ResponseContentType;
var serializer = EndpointHost.AppHost
    .ContentTypeFilters.GetResponseSerializer(contentType);

if (serializer == null)
   throw new Exception("Content-Type {0} does not exist".Fmt(contentType));

var serializationContext = new HttpRequestContext(httpReq, httpRes, dto);
serializer(serializationContext, dto, httpRes);
httpRes.EndServiceStackRequest(); //stops further execution of this request

Note: this just serializes the Response to the Output stream, it does not execute any other Request or Response filters or other user-defined hooks as per a normal ServiceStack request.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!