c# - 在 WCF REST 服务中禁用 XML 示例?

标签 c# .net json wcf rest

我有一个 REST 服务,有多个客户端使用它,据我所知,该服务设置为仅在执行 POST/PUT 时接受 JSON(并且仅在所有调用时返回 JSON)。问题是在服务/帮助页面上,它同时显示了 JSON 和 XML 的示例。有没有一种方法可以删除所有额外的 XML 垃圾以免混淆用户(因为服务只接受 JSON)并且只在/help 页面上显示 JSON 示例?这是我的 Web.config:

<standardEndpoints>
  <webHttpEndpoint>
    <standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="false" defaultOutgoingResponseFormat="Json" />
  </webHttpEndpoint>
</standardEndpoints>

我的每个 GetGets/WebInvokes 都以 JSON 格式定义,例如:

[WebInvoke(UriTemplate = "/sample", BodyStyle = WebMessageBodyStyle.Bare, Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]

那么,还有什么我可以做的让服务知道它是 JSON only 并删除自动生成的 XML 垃圾使我的/help 页面变得困惑吗?

最佳答案

获取你的 Microsoft.ApplicationServer.Http.HttpConfiguration 配置并删除它的 XmlFormatter(它默认有一个 JSON 格式化程序和一个 XML 格式化程序)。

var config = new Microsoft.ApplicationServer.Http.HttpConfiguration();
config.Formatters.Remove(config.Formatters.XmlFormatter);

现在您可以使用此配置创建一个 HttpServiceHostFactory,并使用它来注册路由。

//RouteTable is of type System.Web.Routing.RouteCollection
RouteTable.Add(new WebApiRoute(
    "MyService",
    new HttpServiceHostFactory { Configuration = config },
    typeof(MyService)));

除了“它对我有用”之外,我没有任何可靠的消息来源。

关于c# - 在 WCF REST 服务中禁用 XML 示例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14075004/

相关文章:

c# - 如何基于icalendar格式生成用户友好的消息

c# - 使用 c# SDK Azure.ResourceManager.ApiManagement 导出 OpenAPI 定义

c# - 将数组从一个按钮传递到另一个按钮

c# - 为什么 C# 允许将匿名对象分配给属于类类型的类字段?

javascript - 如果数据库中的值为 true,则如何设置复选框,如果在 angularJS 中编辑时值为 false,则如何取消选中

json - Perl - 取消引用哈希

javascript - 错误类型错误 : Cannot read property '0' of null | Angular 7

c# - 如何关闭由 Graphics.DrawString 执行的布局矩形内的文本填充?

c# - 加速 LINQ 对象查询

c# - 大量日志