如何将默认值添加到自定义ASP.NET配置文件属性

时间:2010-06-16 14:15:48

标签: .net asp.net .net-2.0 asp.net-2.0 profile

我知道您可以使用web.config添加defaultValues,如下所示:

<profile>
    <properties>
        <add name="AreCool" type="System.Boolean" defaultValue="False" />
    </properties>
</profile>

但是我从一个类继承了Profile:

<profile inherits="CustomProfile" defaultProvider="CustomProfileProvider" enabled="true">
  <providers>
    <clear />
    <add name="CustomProfileProvider" type="CustomProfileProvider" />
  </providers>
</profile>

继承班级:

Public Class CustomProfile
    Inherits ProfileBase

    Public Property AreCool() As Boolean
        Get
            Return Me.GetPropertyValue("AreCool")
        End Get
        Set(ByVal value As Boolean)
            Me.SetPropertyValue("AreCool", value)
        End Set
    End Property

End Class

我不知道如何设置属性的默认值。它导致错误,因为没有默认值,它使用一个空字符串,不能转换为布尔值。我尝试添加<DefaultSettingValue("False")> _,但这似乎没有什么区别。

我也在使用自定义ProfileProvider(CustomProfileProvider)。

2 个答案:

答案 0 :(得分:0)

只是一个想法,你可以做这样的事情或一些变化(意味着代替.length,使用dbnull.value(),或者你需要检查它是否是一个真正的项目?

编辑处理空集参数的代码

Public Class CustomProfile     继承ProfileBase

Dim _outBool as boolean
Public Property AreCool() As Boolean 
    Get 
        Return Me.GetPropertyValue("AreCool")
    End Get 
    Set(ByVal value As Object) 
         ''if the value can be parsed to boolean, set AreCool to value, else default to false''
         If([Boolean].TryParse(value, outBool) Then
            Me.SetPropertyValue("AreCool", value)
        Else
            Me.SetPropertyValue("AreCool", False)
        End If

    End Set 
End Property 

结束班

答案 1 :(得分:0)

Microsoft在整个.NET框架中执行此操作的典型方法是使用get部分检查是否可以转换该值,如果不能,则返回默认值。例如:

Public Class CustomProfile 
    Inherits ProfileBase 

    Public Property AreCool() As Boolean 
        Get 
            Dim o as Object = Me.GetPropertyValue("AreCool") 
            If TypeOf o Is Boolean Then
                Return CBool(o)
            End If
            Return False 'Return the default
        End Get 
        Set(ByVal value As Boolean) 
            Me.SetPropertyValue("AreCool", value) 
        End Set 
    End Property 

End Class