【问题标题】:WCF REST reading JSON request bodyWCF REST 读取 JSON 请求正文
【发布时间】:2017-11-25 07:37:09
【问题描述】:

我已经尝试了一周来了​​解如何以 JSON 格式获取和读取 HttpRequest 的请求正文(它以 JSON 格式发送给我)。我认为在我的情况下它是一个 WCF RESTful 服务,但我'我不确定。到目前为止,我走得最远的是使用OperationContext.Current.RequestContext.RequestMessage.ToString(),它为我提供了请求正文的内容,但不是 JSON,而是将其显示为奇怪的 xml 翻译,如下所示:

<root type="object">
<reqPrices type="object">
<regionID type="null"/>
<cityCode type="string">New York</cityCode>
<userName type="string">test</Password>
</obj>
</root>

我有一个 IService 类,代码如下:

namespace TBServices.Services.SilWebApi
{
    [ServiceContract]
    public interface IServiceSilWebApi
    {

        [OperationContract]
        [WebInvoke(Method = "POST", UriTemplate = "prices",
            RequestFormat = WebMessageFormat.Json,
            ResponseFormat = WebMessageFormat.Json,
            BodyStyle = WebMessageBodyStyle.Bare)]
        Stream DoWorkPrices();
     }
}

以及具有以下代码的服务:

    namespace TBServices.Services.SilWebApi
    {
        [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple)]
        public class ServiceSilWebApi : BaseService, IServiceSilWebApi
        {
            ...
             public Stream DoWorkPrices()
            {   
              string aa = OperationContext.Current.RequestContext.RequestMessage.ToString();
              return new Stream();
            }
            ...
         }
     }

配置文件中的相关部分是:

<service name="TBServices.Services.SilWebApi.ServiceSilWebApi">
        <endpoint address="" behaviorConfiguration="web" binding="customBinding" bindingConfiguration="RawReceiveCapable" contract="TBServices.Services.SilWebApi.IServiceSilWebApi" />
 </service>

我是 WCF/REST/SOAP/Web 服务的新手,我已经阅读了有关我正在尝试做的事情的任何内容,无论是在此处还是在 MSDN 中,但我仍然无法弄清楚.我已经看到这个链接有一个与我非常相似的问题:https://social.msdn.microsoft.com/Forums/vstudio/en-US/d3b6307e-886c-4b8a-a7ff-00cd9490520b/read-incoming-data-as-json-wcf?forum=wcf,但我大部分都不明白。 任何帮助将不胜感激!

【问题讨论】:

    标签: c# json web-services rest wcf


    【解决方案1】:

    如果您仅使用 POST 接收数据,则您的方法需要一个参数来接收 POST 数据:

    [OperationContract]
    [WebInvoke(Method = "POST", UriTemplate = "prices",
        RequestFormat = WebMessageFormat.Json,
        ResponseFormat = WebMessageFormat.Json,
        BodyStyle = WebMessageBodyStyle.Bare)]
    Stream DoWorkPrices(string jsonData);
    

    【讨论】:

    • 谢谢,但我已经尝试过了,然后它甚至在运行时都没有转到这个函数,就像它不认为它是匹配的一样
    猜你喜欢
    • 2019-02-18
    • 1970-01-01
    • 2014-06-10
    • 2011-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多