ASP.NET: URI handling

后端 未结 6 2114
暗喜
暗喜 2021-01-06 05:53

I\'m writing a method which, let\'s say, given 1 and hello should return http://something.com/?something=1&hello=en.

I

6条回答
  •  遥遥无期
    2021-01-06 06:20

    This is something that might appeal to you- recently at work I was looking at a way to "type" commonly used URL query string variables and so developed this interface:

       'Represent a named parameter that is passed from page-to-page via a range of methods- query strings, HTTP contexts, cookies, session, etc.
    Public Interface INamedParam
    
        'A key that uniquely identfies this parameter in any HTTP value collection (query string, context, session, etc.)
        ReadOnly Property Key() As String
    
        'The default value of the paramter.
        ReadOnly Property DefaultValue() As Object
    
    End Interface
    

    You can then implement this interface to describe a query string parameter, such an implementation for your "Hello" param might look like this:

    Public Class HelloParam
        Implements INamedParam
    
        Public ReadOnly Property DefaultValue() As Object Implements INamedParam.DefaultValue
            Get
                Return "0"
            End Get
        End Property
    
        Public ReadOnly Property Key() As String Implements INamedParam.Key
            Get
                Return "hello"
            End Get
        End Property
    End Class
    

    I developed a small (and very, very basic) class to help build URLs using these strongly typed parameters:

    Public Class ParametrizedHttpUrlBuilder
    
        Private _RelativePath As String
        Private _QueryString As String
    
        Sub New(ByVal relativePath As String)
            _RelativePath = relativePath
            _QueryString = ""
        End Sub
    
        Public Sub AddQueryParameterValue(ByVal param As INamedParam, ByVal value As Object)
            Dim sb As New Text.StringBuilder(30)
            If _QueryString.Length > 0 Then
                sb.Append("&")
            End If
            sb.AppendFormat("{0}={1}", param.Key, value.ToString())
            _QueryString &= sb.ToString()
        End Sub
    
        Public Property RelativePath() As String
            Get
                Return _RelativePath
            End Get
            Set(ByVal value As String)
                If value Is Nothing Then
                    _RelativePath = ""
                End If
                _RelativePath = value
            End Set
        End Property
    
        Public ReadOnly Property Query() As String
            Get
                Return _QueryString
            End Get
        End Property
    
        Public ReadOnly Property PathAndQuery() As String
            Get
                Return _RelativePath & "?" & _QueryString
            End Get
        End Property
    
    End Class
    

提交回复
热议问题