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

前端 未结 1 531
后悔当初
后悔当初 2021-01-21 03:07

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 with

相关标签:
1条回答
  • 2021-01-21 04:03

    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.

    0 讨论(0)
提交回复
热议问题