gpt4 book ai didi

c# - 没有 DataContract 的 WCF JSON 服务

转载 作者:行者123 更新时间:2023-11-30 17:29:15 24 4
gpt4 key购买 nike

我正在编写一个 WCF 服务,我需要在其中使用 Json 消息,但我不想为其维护数据协定类。这个想法是通过输入流或字符串使用它,然后将其序列化并将其传递到另一个端点。我可以读入它,但输入始终为空。也许有一种方法可以使用动态的 DataContract,但不确定。我可以很好地发送序列化文本 Json 字符串,但我不希望客户只向我发送原始 json 消息,以便我可以将其序列化传递到另一个端点。这可能没有 DataContract 吗?

如果消息是通过 application/json 发送的,则 sMessageIn 始终为 null

[OperationContract]
[WebInvoke(Method = "POST",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "/test"
)]
String RestMessage(String sMessageIn);

使用 JSON(应用程序/json)模式通过 Postman 通过网络发送的输入 Json。

  {
"test": {
"Code": "t",
"Type": "cr"
}
}

最佳答案

是的。有一种解决方案。您可以使用此类作为您的输入,然后将您的动态值传递给它。但不幸的是,您不能将嵌套的 JSON 对象传递给它。

[Serializable]
public class WebServiceDictionary : ISerializable
{
public Dictionary<string, string> Entries { get; }

public WebServiceDictionary()
{
Entries = new Dictionary<string, string>();
}
public WebServiceDictionary(SerializationInfo info, StreamingContext context)
{
Entries = new Dictionary<string, string>();
foreach (var entry in info)
Entries.Add(entry.Name, entry.Value.ToString());
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
foreach (var entry in Entries)
info.AddValue(entry.Key, entry.Value);
}
}

然后你像这样定义你的方法:

[OperationContract]
[WebInvoke(Method = "POST",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/test"
)]
String RestMessage(WebServiceDictionary sMessageIn);

现在你可以传递任何你想要的东西。像这样的事情:

{ “代码”:“t”, “类型”:“cr”

您可以像这样访问字典对象中的参数:

sMessageIn.Entries[Code]

关于c# - 没有 DataContract 的 WCF JSON 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51432929/

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