How to pass an object parameter to a WCF service?

11,345

The problem is that your Login function is marked with the attribute WebGet [WebGet(ResponseFormat = WebMessageFormat.Json)]. You should instead declare your method as WebInvoke:

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

WebGet by default uses a QueryStringConverter class which is unable to convert your complex type. There is a way to get this to work for you if you really need to use WebGet, check out the discussion here for a good explanation of how you would accomplish that.

Take a look at this article for an explanation of WebGet vs WebInvoke. The basics is WebGet should be used with HTTP GET and WebInvoke should be used with other verbs like POST.

Share:
11,345
amarruffo
Author by

amarruffo

Updated on August 01, 2022

Comments

  • amarruffo
    amarruffo almost 2 years

    I'm having this error:

    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'.
    

    I'm trying to pass a parameter to my WCF service, but the service isn't even showing.

    #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
    

    I'm using this:

    $.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.'); }
        });
    

    To call the service, it worked before with a service that recieved 1 string parameter. How can I recieve this object?