如何更改ServiceStack中的默认ContentType?

myt*_*thz 2 .net c# rest web-services servicestack

我在ServiceStack中注册了一个新的内容类型:

appHost.ContentTypeFilters.Register("application/x-my-content-type", 
   SerializeToStream, DeserializeFromStream);
Run Code Online (Sandbox Code Playgroud)

如果客户端在http流中发送内容类型,一切都按预期工作.

不幸的是,我有一个客户端不在我的HTTP Request Heads控制之下,并且不发送内容类型.

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

myt*_*thz 9

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

要覆盖客户端HTTP Accept Header中的Content-type,请附加?format = xml或add.格式扩展

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

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

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

SetConfig(new HostConfig {
     DefaultContentType = "application/x-my-content-type"
});
Run Code Online (Sandbox Code Playgroud)

注意:ServiceStack中的所有配置选项都已设置为打开HostConfig.

从Web浏览器调用Web服务时的问题是,Accept: text/html如果启用了它,它们通常会根据ServiceStack合同要求返回HTML.

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

SetConfig(new HostConfig {
    EnableFeatures = Feature.All.Remove(Feature.Html),
});
Run Code Online (Sandbox Code Playgroud)

否则,如果要覆盖Accept标头,可以强制服务始终通过在HttpResult内修改Response DTO来返回Content-Type,即:

return new HttpResult(dto, "application/x-my-content-type");
Run Code Online (Sandbox Code Playgroud)

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

httpReq.ResponseContentType = "application/x-my-content-type";
Run Code Online (Sandbox Code Playgroud)