VB.NET Web服务 - 从继承类返回ReadOnly属性

时间:2012-09-25 15:58:46

标签: asp.net vb.net

我认为我遗漏了一些非常基本的东西,但这是我的困境。在VB.net中,我创建了一个继承MembershipUser并从Web服务返回对象的类:

Public Class ModifiedUser
    Inherits MembershipUser

用户登录:

Private Sub Login1_Authenticate(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.AuthenticateEventArgs) Handles Login1.Authenticate
    Dim ws As New MembersWS.Members
    Dim Member As New MembersWS.ModifiedUser
    ws.Credentials = System.Net.CredentialCache.DefaultCredentials()
    Member = ws.ValidateUser(Login1.UserName, Login1.Password)
End Sub

在Web服务中创建对象时,ModifiedUser包含MembershipUser的所有属性以及新类的属性。

在我的示例中,ValidateUser函数验证用户并添加其他属性:

Public Function ValidateUser(ByVal UserName As String, ByVal Password As String) As ModifiedUser
    Dim BaseUser As MembershipUser = Membership.Provider.GetUser(UserName, False)
    Dim Member As New ModifiedUser
    If Membership.Provider.ValidateUser(UserName, Password) = True Then 
        Member = New ModifiedUser(BaseUser.ProviderName, BaseUser.UserName, BaseUser.ProviderUserKey, BaseUser.Email, BaseUser.PasswordQuestion, BaseUser.Comment, BaseUser.IsApproved, BaseUser.IsLockedOut, BaseUser.CreationDate, BaseUser.LastLoginDate, BaseUser.LastActivityDate, BaseUser.LastPasswordChangedDate, BaseUser.LastLockoutDate, 0, "", "", "", "", True)
        ' ... (Set new property values)
    End if
    Return Member
End Function

Member返回Login1_Authenticate时,只有在从Web服务返回的对象中包含readonly属性时,才会从对象中删除这些属性。

在Web服务的reference.vb文件中,自动生成的代码包含一个部分MembershipUser类,仅包含可更新的属性以及相关的getter和setter:

Partial Public Class MembershipUser
    Private emailField As String
    Private commentField As String
    Private isApprovedField As Boolean
    Private lastLoginDateField As Date
    Private lastActivityDateField As Date

如果有人可以让我知道如何在返回的对象中包含只读属性,我真的很感激。

1 个答案:

答案 0 :(得分:4)

当Web服务返回包含只读属性的对象时,将始终忽略只读属性。这是因为在客户端,它无法通过设置只读属性的值来反序列化数据。解决此问题的一种方法是向您的属性添加一个setter,它不执行任何操作或抛出异常。例如:

Public Property Id() As Integer
    Get
        Return nID
    End Get
    Set(ByVal Value As Integer)
        Throw New Exception("Cannot set read-only property 'Id'")
    End Set
End Property

有关更多想法,请参阅此问题:

Is it possible to create read only elements in SOAP web services?