ServiceStack 服务非常适合使用 Accept
标头中请求的内容类型进行响应。但是,如果我需要在请求过滤器中提前关闭/结束响应,有没有办法使用正确的内容类型进行响应?我在请求过滤器中可以访问的只是原始 IHttpResponse,所以在我看来,唯一的选择是繁琐地手动检查 Accept
标头并执行一堆开关/case 语句来确定要使用的序列化程序,然后直接写入response.OutputStream
。
为了进一步说明这个问题,在正常的服务方法中,您可以执行以下操作:
public object Get(FooRequest request)
{
return new FooResponseObject()
{
Prop1 = "oh hai!"
}
}
ServiceStack将确定要使用的内容类型以及要使用的序列化程序。我可以在请求过滤器中执行类似操作吗?
ServiceStack 根据许多因素(例如 Accept: header、QueryString 等)预先计算请求的内容类型,并将此信息存储在 httpReq.ResponseContentType
属性中。
您可以将其与IAppHost.ContentTypeFilters
注册表一起使用,该注册表将所有已注册的内容类型序列化程序的集合存储在ServiceStack(即内置+自定义)中,并执行以下操作:
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
注意:这只是将响应序列化到输出流,它不会根据正常的 ServiceStack 请求执行任何其他请求或响应筛选器或其他用户定义的钩子。