【问题标题】:How to pass an object parameter to a WCF service?如何将对象参数传递给 WCF 服务?
【发布时间】:2013-07-28 21:37:01
【问题描述】:

我遇到了这个错误:

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 个字符串参数的服务。 我怎样才能收到这个对象?

【问题讨论】:

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

标签: c# javascript .net wcf


【解决方案1】:

问题是您的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)一起使用。

【讨论】:

  • 您好,我更改了代码,现在可以使用 POST 调用。现在的问题是,在我的 $.ajax 调用中,我使用类型:“POST”,但它被忽略并且使用“GET”,我认为这是因为“dataType:jsonp”。我需要它,因为它是一个跨域调用。所以现在的问题是在使用 JSONP (GET) 时如何发送对象参数。
  • 我没有注意到您使用的是 jsonp。没错,jsonp 调用只能使用 POST。两个建议:1)查看我提供的链接并扩展 QueryStringConverter 以便您可以使用 WebGet 或 2)而不是使用 clsLogin 对象传递复杂类型,只需为“用户名”和“密码”传入两个字符串参数,因为唯一的问题是您正在尝试使用复杂类型。这将是简单易行的。无论哪种方式,我认为您都可以忘记 WebInvoke,因为由于跨域,您的主要需求是 jsonp。如果可行,我可以更新答案。
  • 是的,我会这样做,谢谢!如果您发现可以做任何其他事情来使这更简单(使用多达 5 个以上的参数或类似的东西),那就太好了。
  • 是的,很抱歉,如果不是 jsonp,这将是完美的 :) 我想如果你有很多参数并且它会让你的事情变得更容易,我肯定会扩展 QueryStringConverter。从我链接的答案来看,它看起来很容易做到,但我从未尝试过,所以我不能肯定地告诉你。
猜你喜欢
  • 1970-01-01
  • 2023-03-05
  • 1970-01-01
  • 2015-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多