c# - 除了默认 XML 之外,如何启用更多输出格式?

标签 c# asp.net wsdl

调试 Web 服务时,我可以使用提供的默认 WSDL 接口(interface)来测试功能,该接口(interface)允许我输入一些参数值。这非常方便,但只输出 XML。现阶段是否可以启用更多选项? (JSON、CSV)

或者,如果这是不可能的,我想向 API 调用添加一个额外的参数,filetype=[json,csv],但我该如何以该格式写回它呢?我是否将其作为字符串传递?

最佳答案

我假设您正在使用 WCF。您可以通过多种简单方法在 XML 或 JSON 结果之间进行选择。一是端点不同,二是方法不同。第二个选项可满足您在 API 调用中包含参数的请求,但我将简要描述这两个选项。考虑以下端点:

    <endpoint address="/rest/" behaviorConfiguration="web" binding="webHttpBinding" contract="WebApplication1.Interface.ITestRest" />
    <endpoint address="/json/" behaviorConfiguration="web" binding="webHttpBinding" contract="WebApplication1.Interface.ITestJson" />
    <endpoint address="" behaviorConfiguration="web" binding="webHttpBinding" contract="WebApplication1.Interface.ITestBoth" />

前两个与选项 1 相关,通过端点进行区分(/rest/或/json/将位于方法之前的 url 中,并且两个接口(interface)可以定义相同的签名,因此只需实现一次)。最后一个与选项 2 相关,即在接口(interface)上有两个方法。以下是上述接口(interface)的示例集:

[ServiceContract]
public interface ITestJson
{
  [OperationContract, WebInvoke(Method = "GET", UriTemplate = "/Echo/{Text}",
    RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
  string Echo(string Text);
}

[ServiceContract]
public interface ITestRest
{
  [OperationContract, WebInvoke(Method = "GET", UriTemplate = "/Echo/{Text}",
    RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xml)]
  string Echo(string Text);
}

[ServiceContract]
public interface ITestBoth
{
  [OperationContract, WebInvoke(Method = "GET", UriTemplate = "/Echo?Text={Text}&Format=json",
    RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
  string EchoJ(string Text);
  [OperationContract, WebInvoke(Method = "GET", UriTemplate = "/Echo?Text={Text}&Format=xml",
    RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xml)]
  string EchoR(string Text);
}

然后是一个实现这个的类:

public class Signature : ITestJson, ITestRest, ITestBoth
{
  public string Echo(string Text)
  {
    return Text;
  }

  public string EchoR(string Text)
  {
    return Text;
  }

  public string EchoJ(string Text)
  {
    return Text;
  }

现在您可以通过以下方式使用它:

Service1.svc/json/echo/xxx
Service1.svc/rest/echo/xxx

Service1.svc/echo?Text=xxx&Format=json
Service1.svc/echo?Text=xxx&Format=rest

正如我在开始时所说的,这是选择 XML 或 Json 的几种简单方法。您的请求也要求提供 CSV。目前没有简单的方法返回 CSV。我确实找到了this CodePlex上的项目可以返回TXT,但我还没有检查过。

关于c# - 除了默认 XML 之外,如何启用更多输出格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11323673/

相关文章:

asp.net - 我想在 .NET MVC 中使用剑道网格添加全选复选框

asp.net - 存储 ASP.NET session 变量的最佳解决方案是什么? StateServer 还是 SQLServer?

python - 如何在 zeep 中使用 wsdl 的每种方法发送 header ?

c# - 列中的按钮,获取它来自 Click 事件处理程序的行

使用自定义任务的 C# 任务重写功能

c# - 使用动态变量时可以指定泛型参数吗?

java - 如何在 Netsuite ERP 中使用 SOAP Web 服务获取客户列表?

c# - 将 MyGeneration 与 Fluent NHibernate 结合使用

javascript - 在来自 C# 对象的 Web 应用程序中的 Google map 上创建多个标记点

.net - 使用稍微复杂的方法引用 WCF 服务时获取 "Recursive collection data contract"