我有两个我在下面列出的课程
public Class Vehicle
{
int wheels { get ; set}
}
public Class Car:Vehicle
{
int topspeed { get; set ;}
}
//This is the container class
public Class Message
{
string ConatinerName { get; set;}
Vehicle Container;
}
我已经定义了一个服务合同,如下所示。此Web服务启用了两个端点。一个是SOAP,另一个是Json
//this function gets a message object, looks into the container
public Message GetMessage(Message Input)
{
Car mycar = (Car)Message.Container;
mycar.topspeed = 200;
Message retMessage = new Message();
retMessage.ContainerName ="Adjusted Car Speed";
retMessage.Container = mycar;
return retMessage;
}
当我运行WCF Web服务时,Visual Studio本机测试客户端能够使用Message对象调用该服务,并提供了传递Message容器中的car或vehcile对象的选项。 VS客户端根据传入的原始数据使用soap端点。 测试服务的json端点
我正在使用一个用Python编写的简单客户端,它使用json数据格式调用上述webservice GetMessage()
方法。我传入Car
对象,但服务实际上是
webservice方法获取数据,对象内的容器只包含Vehicle对象。
我已经检查了webmethod收到的请求上下文,它显示接收到正确的json字符串(因为它已发送),但.net以某种方式删除Car
类属性并仅传递Vehicle
属性。因此,在GetMessage()
内投射到汽车会抛出一个异常,说你试图将车辆投射到无效投射的汽车上。
现在我理解Container
中Message
的类型为Vehicle
,但对于SOAP端点,我可以传入汽车对象和车辆对象但是json端点只能通过Message
容器传入Vehicle对象。
我的问题是如何让.NET运行时识别出我正在尝试传递Car
而不是Vehicle
?
我的json客户端代码发布在
下面import urllib2, urllib, json
def get_json(url):
f = urllib2.urlopen(url)
resp = f.read()
f.close()
return json.loads(resp)
def post(url, data):
headers = {'Content-Type': 'application/json'}
request = urllib2.Request(url, data, headers)
f = urllib2.urlopen(request)
response = f.read()
f.close()
return response
geturl = 'http://localhost:24573/Service1.svc/json/GetMessage'
sendurl = 'http://localhost:24573/Service1.svc/json/SendMessage'
msg = get_json(geturl)
print 'Got', msg
print 'Sending...'
retval = post(sendurl, json.dumps(msg))
print 'POST RESPONSE', retval
答案 0 :(得分:4)
我有一个类似的问题,使用Python来调用带有JSON的WCF。值得注意的是,为我确定的是确保__type
密钥在邮件请求中排在第一位。
例如,json.dumps(data, sort_keys=True)
会返回类似这样的内容。 WCF服务不喜欢这样,因为__type
不在Container
中。所以,我的建议是确保__type是第一个。 (另外,我很惊讶sort_keys
不是递归的。)
错:
{"Container": {"Model": "El Camino", "TopSpeed": 150, "Wheels": 0, "__type": "Car:#WcfService1"},"WrapperName": "Car Wrapper"}
右:
{"Container": {"__type": "Car:#WcfService1", "Model": "El Camino", "TopSpeed": 150, "Wheels": 0},"WrapperName": "Car Wrapper"}
简单的python测试客户端。
import urllib2, urllib, json
def get_json(url):
f = urllib2.urlopen(url)
resp = f.read()
f.close()
return json.loads(resp)
def post(url, data):
headers = {'Content-Type': 'application/json'}
request = urllib2.Request(url, data, headers)
f = urllib2.urlopen(request)
response = f.read()
f.close()
return response
geturl = 'http://localhost:24573/Service1.svc/json/GetMessage'
sendurl = 'http://localhost:24573/Service1.svc/json/SendMessage'
msg = get_json(geturl)
print 'Got', msg
print 'Sending...'
retval = post(sendurl, json.dumps(msg))
print 'POST RESPONSE', retval
答案 1 :(得分:0)
将此属性添加到Vehicle类
[KnownType(typeof运算( “汽车”))]