如何改变ServiceStack默认的ContentType?ServiceStack、ContentType

2023-09-03 04:15:36 作者:年少不枉少年

我已经注册一个新的内容类型在ServiceStack有:

I have registered a new content type in ServiceStack with:

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

和一切工作正常,如果客户端发送的HTTP流中的内容类型。

And everything works as expected, if the client sends the content type in the http stream.

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

Unfortunately, I have a client that is not in my control of HTTP Request Heads and does not send the content type.

我怎样才能得到ServiceStack来设置该路由的默认内容类型?

How can I get ServiceStack to set the default content type for that route?

推荐答案

在每ServiceStack /元数据页列出了不同的方式,客户端可以请求一个特定的内容类型:

On every ServiceStack /metadata page lists the different ways a client can request a specific Content-Type:

要覆盖内容类型的客户端的HTTP 接受头,附加的?格式= XML 或补充。格式扩展

To override the Content-type in your clients HTTP Accept Header, append ?format=xml or add .format extension

例如。客户端可以是?格式= X-MY-内容类型指定自定义的ContentType,加入 .X-MY-内容类型延期或通过指定的HTTP标头(在HttpClient的):

E.g. The client can specify your custom ContentType with ?format=x-my-content-type, adding .x-my-content-type extension or by specifying the HTTP Header (in the HttpClient):

接受:应用程序/ x-MY-内容类型

Accept: application/x-my-content-type

否则,如果你的HttpClient不发送和接收报头,你可以在你的APPHOST与指定默认的内容类型:

Otherwise if your HttpClient doesn't send an Accept header you can specify the default content type in your AppHost with:

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

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

从Web浏览器调用Web服务时的问题是,它们通常要求接受:text / html的该合同ServiceStack责成通过返回回来的HTML,如果已启用

The issue when calling web services from a web browser is that they typically ask for Accept: text/html which by contract ServiceStack obliges by returning back HTML if it is enabled.

要确保您的内容类型,总是返回您可能还需要与禁用HTML功能:

To ensure your Content-Type is always returned you may also want to disable the HTML feature with:

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

否则,如果你想为重写接受头,你可以强制您服务,请务必将内容类型由装饰你的回应DTO内的Htt presult,即:

Otherwise if you want to override the Accept header you can force your service to always return your Content-Type by decorating your Response DTO inside a HttpResult, i.e:

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

否则,任何地方你的服务(如请求/响应过滤器),你可以在任何地方设置响应的ContentType之外,有访问 IHtt prequest

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