What is the best way to respond with the right type of content from a request filter in ServiceStack?

ServiceStack services are great for responding with the content type requested in the Accept header. But if I need to close / end the response earlier from the query filter, is there a way to respond with the appropriate type of content? All I have in request filters is a raw IHttpResponse request, so it seems to me that the only option is tedious to manually check the Accept header and do a bunch of switch / case statements to figure out which serializer to use and then write directly to response.OutputStream .

To further illustrate the issue, in a regular service method, you can do something like this:

 public object Get(FooRequest request) { return new FooResponseObject() { Prop1 = "oh hai!" } } 

And ServiceStack will determine which type of content to use and which serializer to use. Is there something like this that I can do as part of a query filter?

+3
source share
1 answer

ServiceStack pre-computes the requested content type for several factors (for example, Accept: header, QueryString, etc.), it stores this information in the httpReq.ResponseContentType property.

You can use this together with the IAppHost.ContentTypeFilters registry, which stores a collection of all serializers of registered content types in ServiceStack (i.e., built-in + user-defined) 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 simply serializes the response to the output stream; it does not execute any other request or response filters or other user hooks in accordance with the usual ServiceStack request.

+2
source

All Articles