作者:雨含的晴天 | 来源:互联网 | 2023-09-06 09:58
我有两个课程,我在下面列出
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()内部投射汽车会抛出一个异常,说你试图将车辆投射到无效演员的汽车上.
现在我理解Message里面的Container是Vehicle类型,但是对于SOAP端点,我能够传入一个car对象和一个车辆对象但是对于json端点,只有一个Vehicle对象可以通过Message传入容器.
我的问题是如何让.NET运行时识别我试图传入汽车而不是车辆?
我的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
解决方法:
我有一个类似的问题使用Python来调用带有JSON的WCF.值得注意的是,为我确定的是确保__type键在post请求中排在第一位.
例如,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