Writing my first VB.NET Class
I am trying to make 2 variables available throughout my site. I am parsing the URL in order to retreive both of them.
This code on the page itself works fine.
Dim countryLanguage As String
countryLanguage = (Request.ServerVariables("URL"))
Dim langVar = (Mid(countryLanguage, 2, 2))
Dim countryVar = (Mid(countryLanguage, 5, 2))
I have created a class file the code for which is below. With this I get a complilation error (BC30451: Name 'Request' is not declared.).
Public Class url_parser
Public Shared F开发者_高级运维unction urlVars(ByVal langVar, ByVal countryVar) As String
Dim countryLanguage As String
countryLanguage = (Request.ServerVariables("URL"))
Dim langVar = (Mid(countryLanguage, 2, 2))
Dim countryVar = (Mid(countryLanguage, 5, 2))
End Function
End Class
Thanks
System.Web.HttpContext.Current.Request
Your page would already be importing System.Web and already references HttpContext.Current for you internally. In an outside class you have to make sure you import the namespace manually and reference the current context.
On a side note, coupling non-page classes to page lifecycle objects (such as HttpContext) is considered bad design. But for getting started it's fine just to make it work. However, I recommend reading up on the MVC pattern and Separation Of Concerns (and Dependency Injection). If you're a beginner programmer it may be a bit advanced, but if you want to program for a long time consider it a worthy goal to set your sights on :)
You can use System.Web.HttpContext.Current.Request
to get the request object for the current thread.
A better way to get your country and language folders is to use Request.Url.Segments
.
Public Class url_parser
Public Shared Function urlLanguage() As String
Dim Request = Web.HttpContext.Current.Request
Return Request.Url.Segments(1).TrimEnd("/"c)
End Function
Public Shared Function urlCountry() As String
Dim Request = Web.HttpContext.Current.Request
Return Request.Url.Segments(2).TrimEnd("/"c)
End Function
End Class
Access these static function this way.
Dim MyLanguage = url_parser.urlLanguage
Dim MyCountry = url_parser.urlCountry
In this example, if the Url is "/en/us/" then...
- Segment(0) is "/"
- Segment(1) is "en/"
- Segment(2) is "us/"
The Request object is generally not available within a simple stand-alone class.
I would recommend you pass the string value of countryLanguage as an additional variable from the call within your page class.
If you really must access the Reqeust object from within the class (not recoemmended) use:
HttpContext.Current.Request
精彩评论