I inherited a vb.net WebForms project that handles a couple domains. However, I want unique routes for each domain. Is there a way to do this by getting the domain when I use MapPageRoute? Or will I need to do something like:
routes.MapPageRoute("r1", "example1/page1", "~/example1/default.aspx")
routes.MapPageRoute("r2", "example2/page1", "~/example2/default.aspx")
But then the urls will need to be like:
//example1.com/example1/page1 and //example2.com/example2/page1
At Application_Start, I'd like to constrain a route to a specific domain, if possible.
* EDIT *
Ok, it looks like I was able to semi-resolve this by creating unique route names for similar route paths:
routes.MapPageRoute("r1", "page1", "~/example1/default.aspx")
routes.MapPageRoute("r2", "page1", "~/example2/default.aspx")
Then in my markup I can do:
<asp:HyperLink NavigateUrl="<%$RouteUrl:routename=r1%>" ID="link_home" runat="server">Home</asp:HyperLink>
Then in my Default page (or its master page), I can then handle the "//example.com/" request by redirecting to the respective route based on the domain.
However I'm not sure how to handle incoming requests like:
//example1.com/page1 and //example2.com/page1. I assume the first route will load for either domain. Any ideas what I can do?
Follow up to my comment:
You can instead create a constraint based on the domain. You'll need to subclass the IRouteConstraint interface.
Where you define your routes:
Dim domain1Constraint As New HostConstraint("domain1.com")
routes.MapPageRoute("r1", "page1", "~/example1/default.aspx", False, Nothing, New RouteValueDictionary(New With {domain1Constraint }))
Then create a class HostConstraint:
Imports System
Imports System.Web.Routing
Public Class HostConstraint
Implements IRouteConstraint
Private _host As String
Public Sub New(ByVal host As String)
_host = host.ToLower()
End Sub
Public Function Match(ByVal httpContext As HttpContextBase, _
ByVal route As Route, _
ByVal parameterName As String, _
ByVal values As RouteValueDictionary, _
ByVal routeDirection As RouteDirection) As Boolean Implements IRouteConstraint.Match
Dim host As String = httpContext.Request.Url.Host.ToLower()
If host.Contains(_host) Then
Return True
Else
Return False
End If
End Function
End Class
Related
With normal HTTP I can download upload and navigate to routers but I can't find any code to do any of that when the routers are on HTTPS.
To download I use this:
Try
My.Computer.Network.DownloadFile("http://" & "180.29.74.70" & "/cgi-bin/log.cgi", "C:\Users\ssb\Desktop\randomword.txt", "username", "password")
WebBrowser1.Refresh()
Catch ex As Exception
MessageBox.Show("Router not sufficient for operation Return for Inspection cannot download log file")
End Try
To upload a file I use this:
My.Computer.Network.UploadFile("C:\Users\ssb\Desktop\tomtn.txt", "http://" & "180.29.74.70" & "/cgi-bin/updateconfig.cgi", "username", "password")
To navigate to a web page on HTTP I use this:
WebBrowser1.Navigate("https://username:password#180.29.74.70 ")
But when I use HTTPS:
WebBrowser1.Navigate("https://username:password#180.29.74.70 ")
I get this security alert:
Then I click on yes and it goes to the page—but I need the code to bypass any security questions like these.
Even though they're loosely related, you've presented two separate questions here.
Why is the call failing when I use the WebBrowser control to load a page via HTTPS?
Why is the call failing when I use the DownloadFile() method to download a file via HTTPS?
First, you need to eliminate the possibility that your code is failing. Try both of the tasks above using public HTTPS URLs that are known to work correctly.
If you discover that the source of the problem is your private URL, you may want to consider whether you want to ignore SSL errors in your WebBrowser control.
You can do so using the (untested, translated to VB) code from this blog post:
Partial Public Class Form1
Inherits Form
Private WithEvents WebBrowser As New WebBrowser
Private Sub WebBrowser_DocumentCompleted(Sender As Object, e As WebBrowserDocumentCompletedEventArgs) Handles WebBrowser.DocumentCompleted
If e.Url.ToString() = "about:blank" Then
'create a certificate mismatch
WebBrowser.Navigate("https://74.125.225.229/")
End If
End Sub
End Class
<Guid("6D5140C1-7436-11CE-8034-00AA006009FA")>
<InterfaceType(ComInterfaceType.InterfaceIsIUnknown)>
<ComImport>
Public Interface UCOMIServiceProvider
<PreserveSig>
Function QueryService(<[In]> ByRef guidService As Guid, <[In]> ByRef riid As Guid, <Out> ByRef ppvObject As IntPtr) As <MarshalAs(UnmanagedType.I4)> Integer
End Interface
<ComImport>
<ComVisible(True)>
<Guid("79eac9d5-bafa-11ce-8c82-00aa004ba90b")>
<InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)>
Public Interface IWindowForBindingUI
<PreserveSig>
Function GetWindow(<[In]> ByRef rguidReason As Guid, <[In], Out> ByRef phwnd As IntPtr) As <MarshalAs(UnmanagedType.I4)> Integer
End Interface
<ComImport>
<ComVisible(True)>
<Guid("79eac9d7-bafa-11ce-8c82-00aa004ba90b")>
<InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)>
Public Interface IHttpSecurity
'derived from IWindowForBindingUI
<PreserveSig>
Function GetWindow(<[In]> ByRef rguidReason As Guid, <[In], Out> ByRef phwnd As IntPtr) As <MarshalAs(UnmanagedType.I4)> Integer
<PreserveSig>
Function OnSecurityProblem(<[In], MarshalAs(UnmanagedType.U4)> dwProblem As UInteger) As Integer
End Interface
Public Class MyWebBrowser
Inherits WebBrowser
Public Shared IID_IHttpSecurity As New Guid("79eac9d7-bafa-11ce-8c82-00aa004ba90b")
Public Shared IID_IWindowForBindingUI As New Guid("79eac9d5-bafa-11ce-8c82-00aa004ba90b")
Public Const S_OK As Integer = 0
Public Const S_FALSE As Integer = 1
Public Const E_NOINTERFACE As Integer = &H80004002
Public Const RPC_E_RETRY As Integer = &H80010109
Protected Overrides Function CreateWebBrowserSiteBase() As WebBrowserSiteBase
Return New MyWebBrowserSite(Me)
End Function
Private Class MyWebBrowserSite
Inherits WebBrowserSite
Implements UCOMIServiceProvider
Implements IHttpSecurity
Implements IWindowForBindingUI
Private myWebBrowser As MyWebBrowser
Public Sub New(myWebBrowser As MyWebBrowser)
MyBase.New(myWebBrowser)
Me.myWebBrowser = myWebBrowser
End Sub
Public Function QueryService(ByRef guidService As Guid, ByRef riid As Guid, ByRef ppvObject As IntPtr) As Integer Implements UCOMIServiceProvider.QueryService
If riid = IID_IHttpSecurity Then
ppvObject = Marshal.GetComInterfaceForObject(Me, GetType(IHttpSecurity))
Return S_OK
End If
If riid = IID_IWindowForBindingUI Then
ppvObject = Marshal.GetComInterfaceForObject(Me, GetType(IWindowForBindingUI))
Return S_OK
End If
ppvObject = IntPtr.Zero
Return E_NOINTERFACE
End Function
Public Function GetWindow(ByRef rguidReason As Guid, ByRef phwnd As IntPtr) As Integer Implements IHttpSecurity.GetWindow, IWindowForBindingUI.GetWindow
If rguidReason = IID_IHttpSecurity OrElse rguidReason = IID_IWindowForBindingUI Then
phwnd = myWebBrowser.Handle
Return S_OK
Else
phwnd = IntPtr.Zero
Return S_FALSE
End If
End Function
Public Function OnSecurityProblem(dwProblem As UInteger) As Integer Implements IHttpSecurity.OnSecurityProblem
'ignore errors
'undocumented return code, does not work on IE6
Return S_OK
End Function
End Class
End Class
Regarding problem #2: It appears you may be confusing WebBrowser and DownloadFile(). As you've probably already discovered, the WebBrowser control doesn't download files. However, you can simulate the behavior using this technique:
Partial Public Class Form2
Inherits Form
Private Sub WebBrowser_Navigating(Sender As Object, e As WebBrowserNavigatingEventArgs) Handles WebBrowser.Navigating
Dim sFilePath As String
Dim oClient As Net.WebClient
' This can be any conditional criteria you wish '
If (e.Url.Segments(e.Url.Segments.Length - 1).EndsWith(".pdf")) Then
SaveFileDialog.FileName = e.Url.Segments(e.Url.Segments.Length - 1)
e.Cancel = True
If SaveFileDialog.ShowDialog() = DialogResult.OK Then
sFilePath = SaveFileDialog.FileName
oClient = New Net.WebClient
AddHandler oClient.DownloadFileCompleted, New AsyncCompletedEventHandler(AddressOf DownloadFileCompleted)
oClient.DownloadFileAsync(e.Url, sFilePath)
End If
End If
End Sub
Private Sub DownloadFileCompleted(Sender As Object, e As AsyncCompletedEventArgs)
MessageBox.Show("File downloaded")
End Sub
Private WithEvents SaveFileDialog As New SaveFileDialog
Private WithEvents WebBrowser As New WebBrowser
End Class
In any event, the first step in solving this is to figure out whether it's your code or the private URL that's causing your issue.
The main thing needed here is to programatically download a file from a https url while using a username and password blocked by the security certificate issue
and the solution after searching for 2 weeks is
To Download a file you can disable the security cerificate request temporaraly with the following code then after the code ran it enables the security certicate again
First code you dont even need a browser it automatically saves the file to you desktop
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'check if a simular file doesnt exists so you can create a new file and deletes the file if it exists
If File.Exists("C:\pathtoyourfile\yourfilename.txt") Then
File.Delete("C:\pathtoyourfile\yourfilename.txt")
End If
'Type this before your download or hhtps request
'ByPass SSL Certificate Validation Checking
System.Net.ServicePointManager.ServerCertificateValidationCallback =
Function(se As Object,
cert As System.Security.Cryptography.X509Certificates.X509Certificate,
chain As System.Security.Cryptography.X509Certificates.X509Chain,
sslerror As System.Net.Security.SslPolicyErrors) True
'Call web application/web service with HTTPS URL here
'=========================================================================================
'ServicePointManager.ServerCertificateValidationCallback = AddressOf AcceptAllCertifications
Try
My.Computer.Network.DownloadFile("https://176.53.78.22/filenameonserveryouwanttodownload", "C:\pathtoyourfile\yourfilename.txt", "Yourusername", "yourpassword")
WebBrowser1.Refresh()
Catch ex As Exception
MessageBox.Show("message saying something didnt work")
'exit sub if it worked
Exit Sub
End Try
MessageBox.Show(" message saying it worked")
'=========================================================================================
'Restore SSL Certificate Validation Checking
System.Net.ServicePointManager.ServerCertificateValidationCallback = Nothing
End Sub
then to browse to a webaddress the following code will popup and the security popup will popup but just select yes browsing on the webpage works normally
WebBrowser1.Navigate("https://username:password#180.29.74.70 ")
As you said:
[...] I need the code to bypass any security questions like these.
In other word, you need to "automatically accept self signed SSL certificate", so in my opinion it is a duplicate question with : VB .net Accept Self-Signed SSL certificate, which may fit your needs.
and most especially slaks answer:
In VB.Net, you need to write:
ServicePointManager.ServerCertificateValidationCallback = AddressOf AcceptAllCertifications
I have website in asp.net web forms. It uses url friendly structure. suppose I have url www.site.com/experience/experience-category. Here there are two different pages experience & experience-category. Now whenever I try to access this url www.site.com/experience/experience-category it doeson't shows me this page. It showing me www.site.com/experience page. How this can be resolved?
RouteConfig
Public Module RouteConfig
Public Sub RegisterRoutes(routes As RouteCollection)
Dim settings = New FriendlyUrlSettings()
settings.AutoRedirectMode = RedirectMode.Permanent
routes.EnableFriendlyUrls(settings)
routes.MapPageRoute("experience-category", "experience/{name}", "~/experience-category.aspx") 'For Experience Category
End Sub
End Module
There's a number of things you can do.
What routes.EnableFriendlyUrls(settings) basically does is adding 2 Routes to your route collection.
Your problem is that you have an .aspx (experience.aspx) with the same name as part of the route url you set up ( experience/{name} ).
The routing will look for the first match in your route collection (in this case it'll be your EnableFriendlyUrls routes).
If you want to overcome this you can do the following:
1.Execute routes.MapPageRoute before routes.EnableFriendlyUrls(settings) :
Public Module RouteConfig
Public Sub RegisterRoutes(routes As RouteCollection)
routes.MapPageRoute("experience-category", "experience/{name}", "~/experience-category.aspx") 'For Experience Category
Dim settings = New FriendlyUrlSettings()
settings.AutoRedirectMode = RedirectMode.Permanent
routes.EnableFriendlyUrls(settings)
End Sub
End Module
This will put this rule first, beating the FriendlyUrlSettings:
Or
2. Use insert to insert your rule at the start of the routes collection (instead of MapPageRoute):
Dim settings = New FriendlyUrlSettings()
settings.AutoRedirectMode = RedirectMode.Permanent
routes.EnableFriendlyUrls(settings)
Dim overwrExperienceUrl As String = "experience/{name}"
Dim overwrExperiencePRH As New PageRouteHandler("~/experience-category.aspx")
Dim overwrExperienceRoute As New Route(overwrExperienceUrl, overwrExperiencePRH)
routes.Insert(0, overwrExperienceRoute)
3.Avoid a match with the EnableFriendlyUrl routing rules:
Move your control(s) (Experience.aspx) to a folder so it won't interfere in this case.
I want to get domain name not for remote ip. i have two domain(website). example www.a1.com and www.a2.com. in a2 domain send a request to a1 domain's page like GetRequest.ashx
the example of http request is
http://www.a1.com/GetRequest.ashx?username=bala&password=123456
in my GetRequest.ashx page example coding
<%# WebHandler Language="VB" Class="Handler" %>
Imports System
Imports System.Web
Public Class GetRequest : Implements IHttpHandler
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
context.Response.ContentType = "text/plain"
Dim username As String = context.Request.QueryString("username")
Dim password As String = context.Request.QueryString("password")
**'//Here i need a coding to get requested domain name that is who send the request to my page**
End Sub
Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
i already use the following coding but not solve my problem. because it return ip address. i need domain only not for ip.
context.Request.ServerVariables("REMOTE_ADDR")
context.Request.ServerVariables("REMOTE_HOST")
Dim domain As String
Dim url As Uri = HttpContext.Current.Request.Url
domain = url.AbsoluteUri.Replace(url.PathAndQuery, String.Empty)
the variable domain contain www.a1.com but i need www.a2.com
use google analytics api to solve my problem? then how to use this api can any one explain
Page.Request.Url.Host contains the host name of the url (www.a1.com in your example)
If a request on the www.a2.com site calls a page on the www.a1.com site, the hostname will always be www.a1.com since that is the host that was used to call the page. I recommend passing a query string variable if you need to know that the request originated from www.a2.com.
You can access the request object through HttpContext, like so:
EDIT: Changed to get host name of referring URL
string host = HttpContext.Current.Request.UrlReferrer.Host;
EDIT: UrlReferrer is returning null. Alternative using HTTP_REFERER:
if (!String.IsNullOrEmpty(Request.ServerVariables["HTTP_REFERER"]))
{
Uri referringUrl = new Uri(Request.ServerVariables["HTTP_REFERER"]);
string referringHostName = referringUrl .Host;
}
Check the Referrer:
HttpContext.Current.Request.UrlReferrer.Host
Inside your code:
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
context.Response.ContentType = "text/plain"
Dim username As String = context.Request.QueryString("username")
Dim password As String = context.Request.QueryString("password")
**'//Here i need a coding to get requested domain name that is who send the request to my page**
Dim domain as string = context.Request.UrlReferrer.Host
End Sub
What's the best way to adjust the path destination for a routing table created in the global.asax Application_Start event based on the domain/sub domain/host? The following worked in IIS6, but with IIS7 the request object is decoupled from the Application_Start event and therefore does not work anymore:
Dim strHost As String = Context.Request.Url.Host
Dim strDir As String = ""
If strHost.Contains("domain1.com") Then
strDir = "area1/"
Else
strDir = "area2/"
End If
routes.MapPageRoute("Search", "Search", "~/" & strDir & "search.aspx")
I seem to have solved my own problem. You can't access the Request object at Application_Start with IIS7.0, though you can use it in a custom route constraint. Here's how I did it.
Define the custom route constraint:
Imports System.Web
Imports System.Web.Routing
Public Class ConstraintHost
Implements IRouteConstraint
Private _value As String
Sub New(ByVal value As String)
_value = value
End Sub
Public Function Match(ByVal httpContext As System.Web.HttpContextBase, ByVal route As System.Web.Routing.Route, ByVal parameterName As String, ByVal values As System.Web.Routing.RouteValueDictionary, ByVal routeDirection As System.Web.Routing.RouteDirection) As Boolean Implements System.Web.Routing.IRouteConstraint.Match
Dim hostURL = httpContext.Request.Url.Host.ToString()
Return hostURL.IndexOf(_value, StringComparison.OrdinalIgnoreCase) >= 0
End Function
End Class
Then define the route:
routes.MapPageRoute(
"Search_Area1",
"Search",
"~/area1/search.aspx",
True,
Nothing,
New RouteValueDictionary(New With {.ArbitraryParamName = New ConstraintHost("domain1.com")})
)
routes.MapPageRoute(
"Search_Area2",
"Search",
"~/area2/search.aspx")
)
This technique can also be used for applying different routing based on the sub-domain as well.
Big thanks to Steven Wather's asp.net mvc routing post for pointing me in the right direction (even though it was for mvc and not web forms).
Is this a setting you could read from web.config instead? <- my recommendation.
Does this post help?
http://mvolo.com/blogs/serverside/archive/2007/11/10/Integrated-mode-Request-is-not-available-in-this-context-in-Application_5F00_Start.aspx
I am looking in to ways to enable a site to basically have something like:
http://mysite.com/en-US/index.aspx`
Where the "en-US" can vary by culture..
This culture in the URL will then basically set the CurrentUICulture for the application..
Basically, we currently have a page where the user explicitly clicks it, but some are favouriting past that, and it is causing some issues..
I know this sort of thing is easily done in ASP.NET MVC, but how about those of us still working in 2.0? Can you guys in all your wisdom offer any suggestions/pointers/ANYTHING that may get me started? This is new to me :)
I'm sure there must be some way to pick up the request and set/bounce as appropriate.. HttpModule maybe?
Update
Just had a thought.. May be best to create VirtDirs in IIS and then pull the appropriate part from the Requested URL and set the culture in InitializeCulture?
Is storing the choice in a cookie out of the question?
Nice of you to give the users a choice but why not just default to the users client/web browser settings?
If they bookmark a page and have lost the cookie you could fall back to the default and if that is a culture you do not support then fallback further to en-US.
If you want to keep your solution you could use a rewrite engine. I've used http://www.managedfusion.com/products/url-rewriter/ in the past. For a list of engines see http://en.wikipedia.org/wiki/Rewrite_engine#IIS
You can use the routing feature developed for MVC easily with webforms. This SO question addresses doing that:
ASP.NET Routing with Web Forms
If you can't use the 3.5 framework, there are a number of URL rewriting modules out there. I have no experience with any to be able to make a recommendation.
I'm doing it in some sites with ASP.net Routing.
Here is the code:
Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
' Code that runs on application startup
RegisterRoutes(RouteTable.Routes)
End Sub
Public Sub RegisterRoutes(ByVal routes As RouteCollection)
Dim reportRoute As Route
Dim DefaultLang As String = "es"
reportRoute = New Route("{lang}/{page}", New LangRouteHandler)
'* if you want, you can contrain the values
'reportRoute.Constraints = New RouteValueDictionary(New With {.lang = "[a-z]{2}"})
reportRoute.Defaults = New RouteValueDictionary(New With {.lang = DefaultLang, .page = "home"})
routes.Add(reportRoute)
End Sub
Then LangRouteHandler.vb class:
Public Class LangRouteHandler
Implements IRouteHandler
Public Function GetHttpHandler(ByVal requestContext As System.Web.Routing.RequestContext) As System.Web.IHttpHandler _
Implements System.Web.Routing.IRouteHandler.GetHttpHandler
'Fill the context with the route data, just in case some page needs it
For Each value In requestContext.RouteData.Values
HttpContext.Current.Items(value.Key) = value.Value
Next
Dim VirtualPath As String
VirtualPath = "~/" + requestContext.RouteData.Values("page") + ".aspx"
Dim redirectPage As IHttpHandler
redirectPage = BuildManager.CreateInstanceFromVirtualPath(VirtualPath, GetType(Page))
Return redirectPage
End Function
End Class
Finally I use the default.aspx in the root to redirect to the default lang used in the browser list.
Maybe this can be done with the route.Defaults, but don't work inside Visual Studio (maybe it works in the server)
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Dim DefaultLang As String = "es"
Dim SupportedLangs As String() = {"en", "es"}
Dim BrowserLang As String = Mid(Request.UserLanguages(0).ToString(), 1, 2).ToLower
If SupportedLangs.Contains(BrowserLang) Then DefaultLang = BrowserLang
Response.Redirect(DefaultLang + "/")
End Sub
Some sources:
* Mike Ormond's blog
* Chris Cavanagh’s Blog
* MSDN
Just try to add that parameter
http://yoursite/yourPage.aspx?lang=en-US
If you were utilizing resources files it will work automatically.
Good Luck