我在asp.net中看到了许多带有WCF的json Web服务的例子,它接受一个in-parameter。我需要我的服务方法来接受许多参数并返回这样的列表;
这是我的Service.svc:
public class Car
{
public string Title;
public int Number;
}
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service
{
[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
public List<Car> GetCarById(int userid, string password , List<Cars> carlist)
{
//Doing some stuff here
}
}
在我的web.config中:
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="ServiceAspNetAjaxBehavior">
<enableWebScript />
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
<services>
<service name="Service">
<endpoint address="" behaviorConfiguration="ServiceAspNetAjaxBehavior"
binding="webHttpBinding" contract="Service" />
</service>
</services>
</system.serviceModel>
如果我想传递所有这些参数,我该如何调用此服务?当我尝试使用params userid,password和carlist调用该方法时,它们都是null。这是我在名为Fiddler的应用程序中使用POST发送给http://localhost/Service.svc/GetCarById的内容:
HEADERS:
Host: localhost
Content-Length: 136
Content-Type: application/json; charset=utf-8
BODY:
{"d":{"password":"test","userid":123,"carlist":[{"__type":"Car","Number":1,"Title":"BMW"},{"__type":"Car","Number":2,"Title":"Honda"}]}}
响应是:{“d”:null}该方法返回carlist,因此我知道该方法被调用并且carlist为null。如果我改变方法返回一个字符串例如“错误”我得到了回来,所以我知道该方法被调用..
你知道我做错了吗?
答案 0 :(得分:1)
终于找到了解决方案:
更改自:
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
只是:
[WebInvoke]
然后我在没有初始“d”的情况下调用了服务,一切都很完美!
感谢您的帮助!
答案 1 :(得分:0)
您可以更改方法的签名吗?如果是这样,为什么不创建一个封装参数的Request对象?像这样:
public class GetCarByIdRequest
{
public int CarId {get;set;}
public int Password {get;set;}
public List<Car> CarList {get;set;}
}