3

ServiceStack services are great for responding with the content type that's requested in the Accept header. But if I need to close/end the response early from within a request filter, is there a way to respond with the proper content type? All I have access to in a request filter is the raw IHttpResponse so it seems to me that the only option is to tediously, 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 the response.OutputStream.

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

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

And ServiceStack will figure out what content type to use and which serializer to use. Is there anything similar to this that I can do within a request filter?

Andrew Young
  • 1,779
  • 1
  • 13
  • 27

1 Answers1

2

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.

mythz
  • 141,670
  • 29
  • 246
  • 390
  • I knew there was a better way. Thanks! – Andrew Young Dec 13 '12 at 01:04
  • I found that it wasn't setting the content type on the response so in addition, you'll need to set the content type as well. `httpRes.ContentType = contentType;` before you `Close()`. – Andrew Young Dec 13 '12 at 18:13
  • @mythz I tried it but i think use the ServiceStack.WebHost.Endpoints.Extensions.HttpResponseExtensions.WriteToResponse(this IHttpResponse httpRes, IHttpRequest httpReq, object result) Method is better – Sword-Breaker Apr 01 '13 at 08:04