2

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

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

4

2 回答 2

2

我假设您正在使用 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 中,并且两个接口可以定义相同的签名,因此只能实现一次)。最后一个与选项 2 相关,在接口上有两种方法。这是上面的一组示例接口:

[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 的简单方法。我确实在 CodePlex 上找到了这个可以返回 TXT​​ 的项目,但我还没有检查出来。

于 2012-07-04T23:26:46.737 回答
1

我建议使用 ASP.NET MVC 3 并创建一个返回 JsonResult 的操作。此 Action 可以执行您的 WebMethod 并将您的结果序列化为 JSON。(这仅适用于 JSON)。

为了获得更大的灵活性,您可以使用 ASP.NET(Web 窗体)通用处理程序,它可以让您对响应类型和内容进行大量控制。

您还可以考虑 ASP.NET MVC 4 中的 Web API 功能。它支持广泛的请求和响应格式。

此堆栈溢出线程涉及 JsonResult 与 Web API:MVC4 Web API 或 MVC3 JsonResult

于 2012-07-04T23:33:31.897 回答