gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 22:27:21 25 4
gpt4 key购买 nike

调试 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com