从 ServiceStack 中的请求过滤器中响应正确的内容类型的最佳方法是什么? [英] What's the best way to respond with the correct content type from request filter in ServiceStack?

查看:39
本文介绍了从 ServiceStack 中的请求过滤器中响应正确的内容类型的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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!"
    }
}

ServiceStack 将确定要使用的内容类型和要使用的序列化程序.我可以在请求过滤器中执行类似的操作吗?

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?

推荐答案

ServiceStack 预先计算请求的内容- 输入多种因素(例如接受:标头、查询字符串等),它将此信息存储在 httpReq.ResponseContentType 属性中.

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.

您可以将它与 IAppHost.ContentTypeFilters 注册表一起使用,该注册表在 ServiceStack(即内置 + 自定义)中存储所有已注册的内容类型序列化程序的集合,并执行以下操作:

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

注意:这只是将响应序列化到输出流,它不会按照正常的 ServiceStack 请求执行任何其他请求或响应过滤器或其他用户定义的钩子.

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.

这篇关于从 ServiceStack 中的请求过滤器中响应正确的内容类型的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆