【问题标题】:How to post complex type to WCF using Python's requests?如何使用 Python 的请求将复杂类型发布到 WCF?
【发布时间】:2014-06-30 14:30:16
【问题描述】:

我正在尝试使用 Python 的 request 包查询 WCF Web 服务。

我在 WCF 中创建了一个非常简单的 Web 服务,遵循默认的 VS 模板:

[ServiceContract]
public interface IHWService
{

    [OperationContract]
    [WebInvoke(Method="GET", UriTemplate="SayHello", ResponseFormat=WebMessageFormat.Json)]
    string SayHello();

    [OperationContract]
    [WebInvoke(Method = "POST", UriTemplate = "GetData", ResponseFormat = WebMessageFormat.Json)]
    string GetData(int value);

    [OperationContract]
    [WebInvoke(Method = "POST", UriTemplate = "GetData2", BodyStyle=WebMessageBodyStyle.Bare,  RequestFormat=WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
    CompositeType GetDataUsingDataContract(CompositeType composite);

    // TODO: Add your service operations here
}

在 Python 中,我设法调用了前两个并轻松取回数据。

但是,我尝试调用第三个,它增加了复杂类型的概念。

这是我的python代码:

import requests as req
import json

wsAddr="http://localhost:58356/HWService.svc"
methodPath="/GetData2"

cType={'BoolValue':"true", 'StringValue':'Hello world'}
headers = {'content-type': 'application/json'}
result=req.post(wsAddr+methodPath,params=json.dumps({'composite':json.dumps(cType)}),headers=headers)

但它不起作用,即,如果我在 GetDataUsingDataContract 方法中的 VS 中进行细分,我看到 composite 参数是 null。我认为这来自解析中的问题,但我不太明白出了什么问题。

你发现那里有明显的错误吗?

你知道我如何在解析机制中进行调试吗?

编辑

这里是复杂类型的定义:

[DataContract]
public class CompositeType
{
    bool boolValue = true;
    string stringValue = "Hello ";

    [DataMember]
    public bool BoolValue
    {
        get { return boolValue; }
        set { boolValue = value; }
    }

    [DataMember]
    public string StringValue
    {
        get { return stringValue; }
        set { stringValue = value; }
    }
}

【问题讨论】:

    标签: python wcf python-2.7 python-requests


    【解决方案1】:

    您需要在 POST 正文中发送 JSON,但您将其附加到查询参数中。

    改用data,并且只编码outer结构:

    result=req.post(wsAddr+methodPath,
                    data=json.dumps({'composite': cType}),
                    headers=headers)
    

    如果您对cType 进行编码,您将发送一个包含另一个 JSON 编码字符串的 JSON 编码字符串,该字符串又包含您的 cType 字典。

    【讨论】:

    • 实际上,现在类型不再为空,但两个字段都没有初始化。我将自定义类型定义添加到问题中
    • @SRKX:我不知道 JSON 如何映射到 WCF 类型。
    • 找到了!只需在 WebInvoke 属性中创建 BodyStyle=WebMessageBodyStyle.WrappedRequest(不是 Bare)。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 2019-04-21
    • 1970-01-01
    • 2012-05-05
    • 1970-01-01
    • 1970-01-01
    • 2015-01-06
    • 1970-01-01
    • 2013-10-20
    相关资源
    最近更新 更多