我有registered a new content type在 ServiceStack 中:
appHost.ContentTypeFilters.Register("application/x-my-content-type",
SerializeToStream, DeserializeFromStream);
如果客户端在 http 流中发送内容类型,一切都会按预期进行。
不幸的是,我有一个客户端不受 HTTP 请求头的控制,并且不发送内容类型。
如何让 ServiceStack 为该路由设置默认内容类型?
最佳答案
在每个 ServiceStack 上 /metadata page列出客户端可以请求特定内容类型的不同方式:
To override the Content-type in your clients HTTP Accept Header, append ?format=xml or add .format extension
例如客户端可以使用 ?format=x-my-content-type、添加 .x-my-content-type
扩展名或通过指定 HTTP header (在 HttpClient 中):
Accept: application/x-my-content-type
否则,如果您的 HttpClient 不发送 Accept header ,您可以在 AppHost 中指定默认内容类型:
SetConfig(new HostConfig {
DefaultContentType = "application/x-my-content-type"
});
注意:ServiceStack 中的所有配置选项都在 HostConfig
上设置。
从 Web 浏览器调用 Web 服务时的问题是,它们通常要求 Accept: text/html
,根据契约(Contract) ServiceStack 必须返回 HTML(如果启用)。
为确保始终返回您的 Content-Type,您可能还想禁用 HTML 功能:
SetConfig(new HostConfig {
EnableFeatures = Feature.All.Remove(Feature.Html),
});
否则,如果您想覆盖 Accept header ,您可以通过在 HttpResult 中装饰您的 Response DTO 来强制您的服务始终返回您的 Content-Type,即:
return new HttpResult(dto, "application/x-my-content-type");
否则,在您的服务之外的任何地方(例如请求/响应过滤器),您可以在任何可以访问 IHttpRequest
的地方设置 Response ContentType:
httpReq.ResponseContentType = "application/x-my-content-type";
关于c# - 如何更改 ServiceStack 中的默认 ContentType?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12326810/