Get Domain Name using asp.net in Generic handler page - asp.net

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

Related

Receive SMS using Twilio and asp.net Webforms

The Twilio documentation provides a guide for asp.net MVC, but not for webforms. I am able to send an SMS message with no problem, but receiving SMS replies is where I am stuck. I have found that it is recommended for webforms users, to use a generic handler, but that is all I have so far, and I do not know how to get the information from the handler. And also, I have to give a URL to the Twilio console and I do not know what URL to give. I can put it on any of my website pages, example "mywebsite.com/??" "??" is I don't know where and how to reference my handler.
I have created the handler "message.ashx" here:
Public Class message : Implements IHttpHandler
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Context.Response.ContentType = "application/xml"
Dim Body = Context.Request.Forms("Body")
Dim response As New Twilio.TwiML.MessagingResponse()
response.Message("You said: " & Body)
Context.Response.Write(response.ToString())
End Sub
Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
So the question is, now that I have this handler in place, how do I get the information on an aspx page to view? And what url do I give to Twilio console for the reply. I am using C# but the answer can be in C# or VB.NET, as I can get translated.
I was able to solve this with the help from comments above. This is Httphandler in aspx webforms. The problem was that they updated their references so having the correct word helped, such as "MessagingResponse", vs. "Twilio.TwiML.MessagingResponse". I also tried migrate my site to MVC, and got it to work with Twilio, but had other issues with the migration. Now I just need to figure out how to actually receive the text that was sent from a user. The Twilio documentation is pretty vague on a lot of things.
Public Class SmsHandler : Implements IHttpHandler
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
context.Response.ContentType = "application/xml"
Dim response = New MessagingResponse
response.Message("Hello World?")
context.Response.Write(response.ToString())
End Sub
Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class

Check to see if currently connected to work network (ldap server)

Firstly, I apologize if i have raised this incorrectly or not quite to the rules. It is my first post.
Can someone please help with my issue.
I have an web application that is fully functioning and authorizes the user.
my problem is that i want to add a check when the site loads to see if the PC is currently connected to the work network. EG. when at home and not connected via VPN I want to redirect to an error page stating not connected to the AD Domain Network.
Currently the app just crashes with exception of "ldap server cannot be reached".
I hope this makes sense.
CODE ADDED
Imports Microsoft.VisualBasic
Imports System.Security.Principal
Imports System.DirectoryServices
Imports System.DirectoryServices.AccountManagement
Imports System.Configuration.ConfigurationManager
Public Class Gen
Dim DomUser As System.DirectoryServices.AccountManagement.UserPrincipal = System.DirectoryServices.AccountManagement.UserPrincipal.Current
Public ADUser As String = AppSettings("DomainPrefix").ToString & DomUser.SamAccountName
Public ADEmail As String = DomUser.EmailAddress
Public ADForname As String = DomUser.GivenName
Public ADSurname As String = DomUser.Surname
Public ADFullName As String = ADForname & " " & ADSurname
Public wi As WindowsIdentity = HttpContext.Current.User.Identity
End Class
Culprit line is
Dim DomUser As System.DirectoryServices.AccountManagement.UserPrincipal = System.DirectoryServices.AccountManagement.UserPrincipal.Current
The best approach is to use the proper OOP paradigm.
Public Function CheckLDAP() As Boolean
Dim DomUser As System.DirectoryServices.AccountManagement.UserPrincipal
Dim blnLDAPOk As Boolean = False
Try
DomUser = System.DirectoryServices.AccountManagement.UserPrincipal.Current
blnLDAPOk = True
Catch ex as Exception
' Perhaps Throw an exception to be handled
End Try
Return blnLDAPOk
End Function
From the class Gen, instantiate the class
Dim gLDAP = New Gen
If (gLDAP.CheckLDAP()) Then
' We are in
Else
' Whoops, no LDAP found
End If

.net routing: Possible to restrict route to a certain domain?

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

How to manitain session values during HttpWebRequest?

In my code I'm sending a HttpWebRequest to a page in my website.
When request sends to this page, It doesn't maintain the Session values.
Below is the code, from where I'm generating the web request:
Public Overloads Shared Function ReadURL(ByVal sUrl As String) As String
Dim sBody As String
Dim oResponse As HttpWebResponse
Dim oRequest As HttpWebRequest
Dim oCookies As New CookieContainer
oRequest = WebRequest.Create("http://localhost:64802/inventory/purchase_order.aspx?id=5654")
oRequest.CookieContainer = oCookies
oResponse = oRequest.GetResponse()
Dim oReader As New StreamReader(oResponse.GetResponseStream())
sBody = oReader.ReadToEnd
oReader.Close()
oResponse.Close()
Return sBody
End Function
Below is the code written on Page_Load of Purchaseorder.aspx.vb:
iDomains_ID = Session("Domains_ID")
iLogin_ID = Session("Login_ID")
sPage = Request.Path
If Request.QueryString.Count > 0 Then sPage &= "?" & Request.QueryString.ToString()
sPage = shared01.Encrypt(sPage, Application("PK"))
If Not User.Identity.IsAuthenticated Or iLogin_ID = 0 Then
Response.Redirect("/login.aspx?page=" & sPage)
Exit Sub
End If
Above code doesn't gets the session values and it redirects to the login page.
So, how i can maintain the session on both pages during HttpWebRequest.
Looking for your replies.
EDIT
I've tried to use CookieContainer class as you can see in above code. But it doesn't work at all.
As an alternative, assuming the calling and called pages are in the same application, you could use the Server.Execute method to load the content of the page without making a separate request to the site:
Public Overloads Function ReadURL(ByVal sUrl As String) As String
Using writer As New StringWriter()
Server.Execute("~/inventory/purchase_order.aspx?id=5654", writer, False)
Return writer.ToString()
End Using
End Function
If I've understood you correctly, you're making a request from one page in your site to another, and you want to send the cookies from the current HttpRequest with your WebRequest?
In that case, you'll need to manually copy the cookies to the CookieContainer:
For Each key As String In Request.Cookies.AllKeys
Dim sourceCookie As HttpCookie = Request.Cookies(key)
Dim destCookie As New Cookie(sourceCookie.Name, sourceCookie.Value, sourceCookie.Path, "localhost")
destCookie.Expires = sourceCookie.Expires
destCookie.HttpOnly = sourceCookie.HttpOnly
destCookie.Secure = sourceCookie.Secure
oCookies.Add(destCookie)
Next
NB: You'll either need to make the ReadUrl function non-Shared, or pass the current HttpRequest as a parameter.
You'll also need to make sure the calling page has EnableSessionState="false" in the <%# Page ... %> directive, otherwise the page you're calling will hang trying to obtain the session lock.
Your code seems like you will need to make a request and a post. The first request will redirect you to your login page. The second will be a request where you post to the login page, which will start the session and (?) store information into the session variables. That post (to the login page) will then redirect you to the page you want.
I used code in this example http://www.codeproject.com/Articles/145122/Fetching-ASP-NET-authenticated-page-with-HTTPWebRe (I tweaked it a bit) to write an application to do this.

How to adjust asp.net URL routing based on domain/host?

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

Resources