【问题标题】:How can you change the default ContentType in ServiceStack?如何更改 ServiceStack 中的默认 ContentType?
【发布时间】:2012-09-01 20:25:39
【问题描述】:

我在 ServiceStack 中有registered a new content type

appHost.ContentTypeFilters.Register("application/x-my-content-type", 
   SerializeToStream, DeserializeFromStream);

如果客户端在 http 流中发送内容类型,一切都会按预期进行。

不幸的是,我有一个不受 HTTP 请求头控制且不发送内容类型的客户端。

如何让 ServiceStack 为该路由设置默认内容类型?

【问题讨论】:

    标签: c# .net web-services rest servicestack


    【解决方案1】:

    在每个 ServiceStack /metadata page 上都列出了客户端请求特定 Content-Type 的不同方式:

    要覆盖客户端 HTTP Accept 标头中的 Content-type,请附加 ?format=xml 或添加 .format 扩展名

    例如客户端可以使用 ?format=x-my-content-type 指定您的自定义 ContentType,添加 .x-my-content-type 扩展名或通过指定 HTTP Header(在 HttpClient 中):

    接受:application/x-my-content-type

    否则,如果您的 HttpClient 不发送 Accept 标头,您可以在 AppHost 中指定默认内容类型:

    SetConfig(new HostConfig {
         DefaultContentType = "application/x-my-content-type"
    });
    

    注意:ServiceStack 中的所有配置选项都设置在HostConfig

    从网络浏览器调用网络服务时的问题是,他们通常要求Accept: text/html,如果启用,ServiceStack 会通过返回 HTML 来强制要求。

    为确保始终返回您的 Content-Type,您可能还需要禁用 HTML 功能:

    SetConfig(new HostConfig {
        EnableFeatures = Feature.All.Remove(Feature.Html),
    });
    

    否则,如果您想覆盖 Accept 标头,您可以通过在 HttpResult 中装饰您的 Response DTO 来强制您的服务始终返回您的 Content-Type,即:

    return new HttpResult(dto, "application/x-my-content-type");
    

    否则,您可以在您的服务之外的任何地方(例如请求/响应过滤器)设置响应 ContentType 任何可以访问 IHttpRequest 的地方:

    httpReq.ResponseContentType = "application/x-my-content-type";
    

    【讨论】:

      猜你喜欢
      • 2013-06-02
      • 2016-08-28
      • 1970-01-01
      • 1970-01-01
      • 2013-01-05
      • 1970-01-01
      • 2012-08-17
      • 2013-09-08
      • 2011-07-12
      相关资源
      最近更新 更多