asp.netweb-serviceswseweb-services-enhancements

web service error ' it does not have a parameterless constructor '


I've created a web service , which can a method to set the user credential using Microsoft.Web.Services3.WebServicesClientProtocol. The sample code is :

<WebMethod()> _
    Public Sub ClientCredential1(Of TSecurityToken As SecurityToken)_
         (ByVal UserCred As Microsoft.Web.Services3.Security.Tokens.UsernameToken)

        Dim cProxy As New Microsoft.Web.Services3.WebServicesClientProtocol()
        cProxy.SetClientCredential(UserCred)
    End Sub

When I run the web service it gives this error:

"Microsoft.Web.Services3.Security.Tokens.UsernameToken cannot be serialized because it does not have a parameterless constructor."

Does any one know where is the problem ?


Solution

  • The root of the problem here is that the class Microsoft.Web.Services3.Security.Tokens.UsernameToken doesn't have a parameter-less constructor. It's got 3 of them, but they all demand a parameter. UsernameToken constructors on MSDN.

    The problem is that during deserialization, XmlSerializer calls the parameterless constructor to create an instance of that class. It can't deserialize a type that doesn't have a parameterless constructor.

    I get the sense there's not much you can do to work around this problem. I'd only suggest creating a partial class, and implementing that zero-param constructor yourself.

    'ensure namespacing is correct.
    Public Partial Class UsernameToken
        Public Sub New()
        End Sub    
    End Class