2009-09-21 51 views
1

我在asp.net中看到了许多使用WCF的json web服务的例子,它们接受一个参数。我需要我的服务方法接受许多参数并返回像这样的列表;使用复杂参数调用.net web服务

这是我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”:空}该方法返回卡洛斯,所以我知道该方法被调用和卡洛斯是空值。如果我改变方法返回一个字符串,例如“错误”我得到了回来,所以我知道这种方法被称为..

你知道我在做什么错了吗?

+0

看到您发送的JSON绝对有帮助,但问题仍然是缺少一个关键部分 - 您用来打电话的客户端JavaScript代码。你确定知道你的服务方法实际上被称为?你如何获得你发送的JSON? – 2009-09-21 17:56:00

+0

是的,我使用Fiddler来测试该方法。用一些信息更新了原始问题。啊哈,看不出有什么问题!谢谢你帮助我! :-) – Martin 2009-09-21 18:18:54

+0

终于搞定了,见最后一个答案.. – Martin 2009-09-21 18:53:55

回答

0

你可以改变你的方法的签名。如果是这样,为什么不创建一个封装参数的Request对象?就像这样:

public class GetCarByIdRequest 
{ 
    public int CarId {get;set;} 
    public int Password {get;set;} 
    public List<Car> CarList {get;set;} 
} 
+0

感谢您的帮助!我真正需要做的是将List作为参数发送到我的方法中。但我无法弄清楚如何将数据发布到我的方法。你知道在哪里可以找到如何做到这一点的例子吗? – Martin 2009-09-21 13:17:21

1

终于找到了解决办法:

[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)] 

要刚:

更改从

[WebInvoke] 

然后我叫不最初的“d服务“,一切都很完美!

感谢您的帮助!

+0

请设置此问题为自己解决 – 2010-09-21 15:54:07