如何将对象参数传递给WCF服务?

4
我正在遇到这个错误:
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个字符串参数的服务是有效的。 如何接收该对象?


是的,我之前有一个类似的服务在运行,但它只接收一个字符串参数,而这个需要接收一个对象。这是我调用它的语法(编辑了第一篇帖子)。 - amarruffo
请查看此帖子 http://stackoverflow.com/questions/9334643/wcf-rest-webget-for-user-defined-parameters - Kambiz Shahim
1个回答

3
问题在于你的 Login 函数被标记为 WebGet 属性 [WebGet(ResponseFormat = WebMessageFormat.Json)]。你应该将你的方法声明为 WebInvoke
[OperationContract]
[WebInvoke(ResponseFormat = WebMessageFormat.Json)]
public Int32 Login(clsLogin objLogin)

WebGet默认使用QueryStringConverter类,该类无法转换您的复杂类型。如果您确实需要使用WebGet,则有一种方法可以使其适用于您,请查看此处的讨论,了解如何实现。

阅读本文WebGet vs WebInvoke的说明。基本上,WebGet应与HTTP GET一起使用,而WebInvoke应与其他动词(如POST)一起使用。


你好,我修改了我的代码,现在它可以使用POST调用。但问题是,在我的$.ajax调用中,我使用了type: "POST",但它被忽略了,而是使用了"GET"。我认为这是因为"dataType: jsonp"的缘故。由于这是跨域调用,我需要这个。所以现在的问题是如何在使用JSONP(GET)时发送对象参数。 - amarruffo
我没有注意到你在使用jsonp。你是对的,jsonp调用只能使用POST方法。我的两个建议是:1)查看我提供的链接并扩展QueryStringConverter,以便您可以使用WebGet传递复杂类型;2)不要使用clsLogin对象,而是直接传递两个字符串参数“username”和“password”,因为唯一的问题是您正在尝试使用复杂类型。这将非常简单和容易。无论哪种方式,我认为您可以忘记WebInvoke,因为由于跨域,您的主要需求是jsonp。如果这行得通,我会更新答案。 - p e p
好的,我会这样做,谢谢!如果你发现任何其他可以使它更简单的方法(例如使用5个或更多参数之类的),那就太棒了。 - amarruffo
是的,抱歉,如果不涉及jsonp,这将是完美的 :) 我认为如果你有很多参数并且它可以让事情变得更容易,我肯定会选择扩展QueryStringConverter。从我链接的答案中看来,这似乎非常容易实现,但我从未尝试过,所以无法确定告诉你。 - p e p

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接