2013-07-28 110 views
3

我有此错误:如何将对象参数传递给WCF服务?

Operation 'Login' in contract 'Medicall' has a query variable named 'objLogin' of type  'Medicall_WCF.Medicall+clsLogin', but type 'Medicall_WCF.Medicall+clsLogin' is not convertible by 'QueryStringConverter'. Variables for UriTemplate query values must have types that can be converted by 'QueryStringConverter'. 

我想一个参数传递给我的WCF服务,但该服务甚至没有显示。

#region Methods 
    [OperationContract] 
    [WebGet(ResponseFormat = WebMessageFormat.Json)] 
    public Int32 Login(clsLogin objLogin) 
    { 
     try 
     { 
      // TODO: Database query. 
      if (objLogin.username == "" & objLogin.password == "") 
       return 1; 
      else 
       return 0; 
     } 
     catch (Exception e) 
     { 
      // TODO: Handle exception error codes. 
      return -1; 
     } 
    } 

    #endregion 
    #region Classes 
    [DataContract(), KnownType(typeof(clsLogin))] 
    public class clsLogin 
    { 
     public string username; 
     public string password; 
    } 
    #endregion 

我使用这个:

$.ajax({ 
     url: "PATH_TO_SERVICE", 
     dataType: "jsonp", 
     type: 'post', 
     data: { 'objLogin': null }, 
     crossDomain: true, 
     success: function (data) { 
      // TODO: Say hi to the user. 
      // TODO: Make the menu visible. 
      // TODO: Go to the home page. 
      alert(JSON.stringify(data)); 
     }, 
     failure: function (data) { app.showNotification('Lo sentimos, ha ocurrido un error.'); } 
    }); 

调用服务,将其与收到1个字符串参数的服务工作过。 我该如何接收这个对象?

+0

是的,我有一个类似的服务工作,但它只收到1个字符串参数,因为这个我需要它来接收一个对象。这是我用来调用它的语法(编辑第一篇文章)。 – amarruffo

+0

看到这篇文章http://stackoverflow.com/questions/9334643/wcf-rest-webget-for-user-defined-parameters –

回答

2

问题是您的Login功能被标记为属性WebGet[WebGet(ResponseFormat = WebMessageFormat.Json)]。你应该将你的申报方法WebInvoke

[OperationContract] 
[WebInvoke(ResponseFormat = WebMessageFormat.Json)] 
public Int32 Login(clsLogin objLogin) 

WebGet默认使用一个QueryStringConverter类,这是不能转换的复杂类型。如果你真的需要使用WebGet,有一种方法可以让你为你工作,请参考here的讨论,了解你将如何完成该任务。

看一看这篇文章的WebGet vs WebInvoke的解释。基本知识是WebGet应该与HTTP GET一起使用,并且WebInvoke应该与POST等其他动词一起使用。

+0

你好,我改变了我的代码,现在它与POST调用。现在的问题是,在我的$ .ajax调用中,我使用type:“POST”,但它被忽略,它使用“GET”我认为这是因为“dataType:jsonp”。我需要这个,因为它是一个跨域呼叫。所以现在的问题是如何使用JSONP(GET)发送对象参数。 – amarruffo

+0

我没有注意到您正在使用jsonp。你是对的,jsonp调用只能使用POST。两个建议:1)看看我提供的链接并扩展QueryStringConverter,以便可以使用WebGet或2)传递复杂类型,而不是使用clsLogin对象,只需传入两个字符串参数“username”和“password”,因为唯一的问题是您正在尝试使用复杂类型。这将是简单和容易的。无论哪种方式,我认为你可以忘记WebInvoke,因为你的主要需求是跨域的jsonp。如果这有效,我可以更新答案。 –

+0

是的,我会这么做,谢谢!如果你发现任何其他的事情可以做到这一点更简单(使用多达5 +参数或类似的东西),这将是很好的。 – amarruffo

相关问题