【问题标题】:What's the best way to respond with the correct content type from request filter in ServiceStack?从 ServiceStack 中的请求过滤器中使用正确的内容类型响应的最佳方式是什么?
【发布时间】:2012-12-13 00:31:34
【问题描述】:

ServiceStack 服务非常适合使用 Accept 标头中请求的内容类型进行响应。但是,如果我需要在请求过滤器中尽早关闭/结束响应,有没有办法以正确的内容类型进行响应?我在请求过滤器中可以访问的只是原始 IHttpResponse 所以在我看来唯一的选择是繁琐地手动检查 Accept 标头并执行一堆 switch/case 语句来确定要使用的序列化程序和然后直接写信给response.OutputStream

为了进一步说明问题,在正常的服务方法中,您可以执行以下操作:

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

ServiceStack 将确定要使用的内容类型以及要使用的序列化程序。我可以在请求过滤器中做任何类似的事情吗?

【问题讨论】:

    标签: servicestack


    【解决方案1】:

    ServiceStack 根据许多因素(例如 Accept: header、QueryString 等)预先计算 Requested Content-Type,并将此信息存储在 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 请求执行任何其他请求或响应过滤器或其他用户定义的挂钩。

    【讨论】:

    • 我知道有更好的方法。谢谢!
    • 我发现它没有在响应中设置内容类型,所以此外,您还需要设置内容类型。 httpRes.ContentType = contentType; 在你之前Close()
    • @mythz 我试过了,但我认为使用 ServiceStack.WebHost.Endpoints.Extensions.HttpResponseExtensions.WriteToResponse(this IHttpResponse httpRes, IHttpRequest httpReq, object result) 方法更好
    猜你喜欢
    • 2017-03-16
    • 1970-01-01
    • 2013-05-28
    • 2012-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-07
    相关资源
    最近更新 更多