I have a web service that transfers a file, and i want to authenticate that the source of the transfer has access. I authenticate all my clients by their user SID that gets pulled from AD, which is then encrypted and stored in a DB. The problem i am running into is that the client transferring the file calls the service every 49152 bytes. So basically I dont want it to make a DB call every time a new byte array comes in. Any idea how i could just make it call the DB once to verify the encrypted SID is authenticated once and then trust it until complete?
Here is my code:
public class TransferFile : System.Web.Services.WebService
{
int Authenticated = 0;
[WebMethod]
public void WriteBinaryFile(string userSID, byte[] buffer, string FileName)
{
string ConnectionString = null;
string DBServer = null;
string AuthenticationMethod = null;
string DB_U = null;
string DB_P = null;
string DBName = null;
try
{
XmlReader xmlReader = XmlReader.Create(#"C:\Program Files\SM\SM_DB_Config.xml");
while (xmlReader.Read())
{
if ((xmlReader.NodeType == XmlNodeType.Element) && (xmlReader.Name == "DB_Server"))
{
string strUsername = null;
strUsername = xmlReader.ReadInnerXml().ToString();
if (strUsername.ToString() == "")
{
}
else
{
DBServer = SpartaCrypto.SpartaDecryptAES(strUsername, "secretcode");
}
}
if ((xmlReader.NodeType == XmlNodeType.Element) && (xmlReader.Name == "DB_Name"))
{
string strUsername = null;
strUsername = xmlReader.ReadInnerXml().ToString();
if (strUsername.ToString() == "")
{
}
else
{
DBName = SpartaCrypto.SpartaDecryptAES(strUsername, "secretcode");
}
}
if ((xmlReader.NodeType == XmlNodeType.Element) && (xmlReader.Name == "DB_AuthenticationMethod"))
{
string strUsername = null;
strUsername = xmlReader.ReadInnerXml().ToString();
if (strUsername.ToString() == "")
{
}
else
{
AuthenticationMethod = SpartaCrypto.SpartaDecryptAES(strUsername, "secretcode");
}
}
if ((xmlReader.NodeType == XmlNodeType.Element) && (xmlReader.Name == "DB_U"))
{
string strUsername = null;
strUsername = xmlReader.ReadInnerXml().ToString();
if (strUsername.ToString() == "")
{
}
else
{
DB_U = SpartaCrypto.SpartaDecryptAES(strUsername, "secretcode");
}
}
if ((xmlReader.NodeType == XmlNodeType.Element) && (xmlReader.Name == "DB_P"))
{
string strUsername = null;
strUsername = xmlReader.ReadInnerXml().ToString();
if (strUsername.ToString() == "")
{
}
else
{
DB_P = SpartaCrypto.SpartaDecryptAES(strUsername, "secretcode");
}
}
}
xmlReader.Close();
if (AuthenticationMethod == "Integrated")
{
ConnectionString = "Data Source=" + DBServer + ";Provider=SQLOLEDB;Initial Catalog=" + DBName + ";Integrated Security=SSPI;";
}
else
{
ConnectionString = "Data Source=" + DBServer + ";Provider=SQLOLEDB;Initial Catalog=" + DBName + ";User ID=" + DB_U + ";Password=" + DB_P;
}
String query = "SELECT COUNT(AD_SID) As ReturnCount FROM AD_Authorization WHERE AD_SID = ?";
OleDbConnection conn = new OleDbConnection(ConnectionString);
OleDbCommand cmd = new OleDbCommand(query, conn);
cmd.Parameters.AddWithValue("userSID", userSID.ToString());
conn.Open();
int returnCount = (Int32)cmd.ExecuteScalar();
conn.Close();
if (returnCount >= 1)
{
Authenticated = 1;
}
else
{
Authenticated = 0;
}
}
catch (Exception ex)
{
}
if (Authenticated == 1)
{
string PathName = #"C:\Test\";
using (FileStream fs = new FileStream(PathName + FileName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite))
{
fs.Seek(0, SeekOrigin.End);
fs.Write(buffer, 0, buffer.Length);
}
}
}
}
If your only concern is hitting the db frequently, I would suggest you cache the SID in your webservice as authenticated. Whenever you get a request, check if the value exists in the cache and if it is not there, then hit the db. Also you should set a optimal time for expiration.
You could use HttpRuntime.Cache for this purpose.
Code to set the value in Cache
HttpRuntime.Cache.Insert(userSID, 1, null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(0, 5, 0))
Code to get the value from Cache
HttpRuntime.Cache.Get(userSID)
Maybe you can save the first result in the ASP.NET Cache. See http://msdn.microsoft.com/en-us/library/aa480499.aspx
You can save objects (like the validation variable) in cache like this:
var Authenticated = ... (the value that you already have)
HttpContext.Current.Cache.Insert(
"myAuthenticatedCacheKey",
Authenticated,
null, DateTime.Now.AddMinutes(10), // 10 minutes expiration
System.Web.Caching.Cache.NoSlidingExpiration
);
And you can recover them like this:
var Authenticated = HttpContext.Current.Cache.Get("myAuthenticatedCacheKey");
Another way to go could be using the Application object (The same as the Session object but with an application scope and it is shared between all the sessions). You can store and retrieve objects from the Application scope like the following:
Session("myAuthenticatedSessionKey") = Authenticated;
...
var Authenticated = Session("myAuthenticatedSessionKey");
Please notice that you need to cast the objects when retrieving them from Cache or Application objects.
Related
Never worked with Active Directory and need help with updating a users record in Active Directory. This is in an ASP.NET web application.
String objLdapConnection = ConfigurationManager.ConnectionStrings["ADConnection"].ToString();
DirectorySearcher objSearcher = new DirectorySearcher(objLdapConnection);
objSearcher.Filter = "(sAMAccountName=" + this.txtAccount.Text + ")";
SearchResult objResult = objSearcher.FindOne();
if (objResult != null)
{
DirectoryEntry objUpdateEntry = objResult.GetDirectoryEntry();
if (this.txtWorkPhone.Text != strWorkPhone)
objUpdateEntry.Properties["telephoneNumber"].Value = this.txtWorkPhone.Text;
if (this.txtExtension.Text != strExtension)
objUpdateEntry.Properties["ipPhone"].Value = this.txtExtension.Text;
if (this.ddlOffice.SelectedItem.Text != strOffice)
objUpdateEntry.Properties["l"].Value = this.ddlOffice.SelectedItem.Text;
if (this.ddlDepartment.SelectedItem.Text != strDepartment)
objUpdateEntry.Properties["department"].Value = this.ddlDepartment.SelectedItem.Text;
if (this.txtJobTitle.Text != strTitle)
objUpdateEntry.Properties["title"].Value = this.txtJobTitle.Text;
if (this.txtSupervison.Text != strSuperVisor)
objUpdateEntry.Properties["manager"].Value = this.txtSupervison.Text;
objUpdateEntry.CommitChanges();
}
else
{
this.lblresult.Text = "Account was not found";
}
Given code is working properly but while checking page url on redirect checker,it gives error as too many redirections which may affect on performace of app.
if (Request.QueryString[null] != null)
{
string LastIndexOFUrl = Request.RawUrl.Substring(Request.RawUrl.LastIndexOf('/') + 1);
if (lang == "eng")
{
//Session["ServiceName"] = Request.QueryString[null].ToString();
//
dt2 = FEManager.GetOurServiceByID(CommonFunction.GetLangType(), LastIndexOFUrl);
if (dt2.Rows.Count > 0)
{
string Name_En = dt2.Rows[0]["URLEng"].ToString();
Name_En = Regex.Replace(Name_En, "[^0-9A-Za-z -]", "").ToLower().Replace(' ', '-');
if (Convert.ToString(Session["ServiceName"]) != Name_En)
{
Session["ServiceName"] = Name_En;
Response.Redirect(CommonFunction.GetLangWiseRedirectLink(1428, 1429) + "/" + Name_En);
}
else
Session["ServiceName"] = Name_En;
}
//
}
else
{
Session["ServiceName"] = Request.RawUrl.Substring(Request.RawUrl.LastIndexOf('/') + 1);
//temp code:
dt1 = FEManager.GetOurServiceByID(CommonFunction.GetLangType(), Session["ServiceName"].ToString());
if (dt1.Rows.Count > 0)
{
if (Session["ServiceName"].ToString() != dt1.Rows[0]["URLAr"].ToString())
{
Response.Redirect(CommonFunction.GetLangWiseRedirectLink(1428, 1429) + "/" + dt1.Rows[0]["URLAr"].ToString());
}
Session["ServiceName"] = dt1.Rows[0]["URLAr"].ToString();
}
}
string sessionData1 = Session["ServiceName"].ToString();
}
else
{
if (Session["ServiceName"] == null)
{
Response.Redirect(CommonFunction.GetLangWiseRedirectLink(1342, 1343));
}
else
{
Response.Redirect(CommonFunction.GetLangWiseRedirectLink(1428, 1429) + "/" + Session["ServiceName"].ToString());
}
}
dt = FEManager.GetOurServiceByID(CommonFunction.GetLangType(), Session["ServiceName"].ToString());
if (dt.Rows.Count > 0)
{
ltContent.Text = dt.Rows[0]["longDesc"].ToString();
ltHeader.Text = dt.Rows[0]["name"].ToString();
hdnID.Value = dt.Rows[0]["ID"].ToString();
((DotNetNuke.Framework.CDefault)this.Page).Title = dt.Rows[0]["pageTitle"].ToString();
}
If you get "too many redirects" it's almost always because you have created an infinite loop of redirects by redirecting to the same page.
Step through the code in a debugger and carefully check the redirect urls.
Hi I would like to get and count all the invalid accounts from the method valSAM using my other method GetSAM.
I've managed to use the count property to get the total number of accounts in the database from the GetSAM method. (lines 7- 23, GetSAM) The problem is, I do not know how to replicate that and call/ count the total number of invalid accounts from the valSAM method. (lines 20- 39, valSAM)
I have a hunch that I have to somehow call the invalid accounts to the GetSAM method before I am able to call them as well but I do not know how to implement it. Can anyone please advise me on this?
GetSAM method:
//Get SAMAccount
private static string GetSAM(string ldapAddress, string serviceAccountUserName, string serviceAccountPassword)
{
string ldapPath = "LDAP://" + ldapAddress;
string ldapFilter = "(&(objectclass=user)(objectcategory=person))";
DirectoryEntry directoryEntry = new DirectoryEntry(ldapPath, serviceAccountUserName, serviceAccountPassword);
string readOutput;
List<string> list = new List<string>();
StringBuilder builder = new StringBuilder();
using (DirectorySearcher directorySearcher = new DirectorySearcher(directoryEntry))
{
string samAccountName;
directorySearcher.Filter = ldapFilter;
directorySearcher.SearchScope = SearchScope.Subtree;
directorySearcher.PageSize = 1000;
using (SearchResultCollection searchResultCollection = directorySearcher.FindAll())
{
foreach (SearchResult result in searchResultCollection)
{
samAccountName = result.Properties["sAMAccountName"][0].ToString();
valSAM(samAccountName, ldapAddress, serviceAccountUserName, serviceAccountPassword);
list.Add(samAccountName);
} //end of foreach
// Count all accounts
int totalAccounts = list.Count;
Console.WriteLine("Found " + totalAccounts + " accounts. Query in " + ldapAddress + " has finished.\n");
Console.WriteLine("Press [enter] to continue.\n");
readOutput = Console.ReadLine();
}//SearchResultCollection will be disposed here
}
return readOutput;
}
valSAM method:
//Validate SAMAccount
private static string valSAM(string samAccountName, string ldapAddress, string serviceAccountUserName, string serviceAccountPassword)
{
string ldapPath = "LDAP://" + ldapAddress;
DirectoryEntry directoryEntry = new DirectoryEntry(ldapPath, serviceAccountUserName, serviceAccountPassword);
StringBuilder builder = new StringBuilder();
//create instance fo the directory searcher
DirectorySearcher desearch = new DirectorySearcher(directoryEntry);
//set the search filter
desearch.Filter = "(&(sAMAccountName=" + samAccountName + ")(objectcategory=user))";
//find the first instance
SearchResult results = desearch.FindOne();
using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, ldapAddress))
{
//if users are present in database
if (results != null)
{
//Check if account is activated
bool isAccountActived = IsActive(results.GetDirectoryEntry());
//Check if account is expired or locked
bool isAccountLocked = IsAccountLockOrExpired(results.GetDirectoryEntry());
//account is invalid
if ((isAccountActived != true) || (isAccountLocked))
{
builder.Append("User account " + samAccountName + " is invalid. ");
if ((isAccountActived != true) && (isAccountLocked))
{
builder.Append("Account is inactive and locked or expired.").Append('\n'); ;
} else if (isAccountActived != true)
{
builder.Append("Account is inactive.").Append('\n'); ;
}
else if (isAccountLocked)
{
builder.Append("Account is locked or has expired.").Append('\n'); ;
}
else
{
builder.Append("Unknown reason for status. Contact admin for help.").Append('\n'); ;
}
}
//account is valid
if ((isAccountActived) && (isAccountLocked != true))
{
builder.Append("User account " + samAccountName + " is valid.").Append('\n');
}
}
else Console.WriteLine("Nothing found.");
Console.WriteLine(builder);
}
return builder.ToString();
}
Updated valSAM:
//Validate SAMAccount
private static bool valSAM(string samAccountName, string ldapAddress, string serviceAccountUserName, string serviceAccountPassword)
{
string ldapPath = "LDAP://" + ldapAddress;
DirectoryEntry directoryEntry = new DirectoryEntry(ldapPath, serviceAccountUserName, serviceAccountPassword);
StringBuilder builder = new StringBuilder();
bool accountValidation = true;
//create instance fo the directory searcher
DirectorySearcher desearch = new DirectorySearcher(directoryEntry);
//set the search filter
desearch.Filter = "(&(sAMAccountName=" + samAccountName + ")(objectcategory=user))";
//find the first instance
SearchResult results = desearch.FindOne();
using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, ldapAddress))
{
//if users are present in database
if (results != null)
{
//Check if account is activated
bool isAccountActived = IsActive(results.GetDirectoryEntry());
//Check if account is expired or locked
bool isAccountLocked = IsAccountLockOrExpired(results.GetDirectoryEntry());
accountValidation = ((isAccountActived != true) || (isAccountLocked));
//account is invalid
if (accountValidation)
{
builder.Append("User account " + samAccountName + " is invalid. ");
if ((isAccountActived != true) && (isAccountLocked))
{
builder.Append("Account is inactive and locked or expired.").Append('\n'); ;
} else if (isAccountActived != true)
{
builder.Append("Account is inactive.").Append('\n'); ;
}
else if (isAccountLocked)
{
builder.Append("Account is locked or has expired.").Append('\n'); ;
}
else
{
builder.Append("Unknown reason for status. Contact admin for help.").Append('\n'); ;
}
return false;
}
//account is valid
if ((isAccountActived) && (isAccountLocked != true))
{
builder.Append("User account " + samAccountName + " is valid.").Append('\n');
return true;
}
}
else Console.WriteLine("Nothing found.");
Console.WriteLine(builder);
Console.ReadLine();
}//end of using
return accountValidation;
}
Thanks a million :)
Update: Now I have a new problem after updating my valSAM- I am unable to print out the accounts when I return the boolean accountValidation instead of builder.ToString().
You are returning the call before you do Console.WriteLine, do something like this:
private static bool valSAM(string samAccountName, string ldapAddress, string serviceAccountUserName, string serviceAccountPassword)
{
string ldapPath = "LDAP://" + ldapAddress;
DirectoryEntry directoryEntry = new DirectoryEntry(ldapPath, serviceAccountUserName, serviceAccountPassword);
StringBuilder builder = new StringBuilder();
bool accountValidation = true;
//create instance fo the directory searcher
DirectorySearcher desearch = new DirectorySearcher(directoryEntry);
//set the search filter
desearch.Filter = "(&(sAMAccountName=" + samAccountName + ")(objectcategory=user))";
//find the first instance
SearchResult results = desearch.FindOne();
using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, ldapAddress))
{
//if users are present in database
if (results != null)
{
//Check if account is activated
bool isAccountActived = IsActive(results.GetDirectoryEntry());
//Check if account is expired or locked
bool isAccountLocked = IsAccountLockOrExpired(results.GetDirectoryEntry());
accountValidation = ((isAccountActived != true) || (isAccountLocked));
//account is invalid
if (accountValidation)
{
builder.Append("User account " + samAccountName + " is invalid. ");
if ((isAccountActived != true) && (isAccountLocked))
{
builder.Append("Account is inactive and locked or expired.").Append('\n'); ;
} else if (isAccountActived != true)
{
builder.Append("Account is inactive.").Append('\n'); ;
}
else if (isAccountLocked)
{
builder.Append("Account is locked or has expired.").Append('\n'); ;
}
else
{
builder.Append("Unknown reason for status. Contact admin for help.").Append('\n'); ;
}
accountValidation = false;
}
//account is valid
if ((isAccountActived) && (isAccountLocked != true))
{
builder.Append("User account " + samAccountName + " is valid.").Append('\n');
accountValidation = true;
}
}
else Console.WriteLine("Nothing found.");
Console.WriteLine(builder);
Console.ReadLine();
}//end of using
return accountValidation;
}
So now, you can assign the value and have one return point and can also print the names. As for keeping track of counts in main function you can place valSAM call in
if(valSAM(samAccountName, ldapAddress, serviceAccountUserName, serviceAccountPassword))
{
invalidAccountCount++;
}
And needless to say, you have to initialize invalidAccountCount outside the loop.
How to check login user name from the system in c#
I tried it using this method
static string whoisLoggedIn(string HostOrIP)
{
GUFlag = true;
HostOrIP = Environment.MachineName;
System.Management.ConnectionOptions myConnectionOptions = new System.Management.ConnectionOptions();
myConnectionOptions.Impersonation = System.Management.ImpersonationLevel.Impersonate;
System.Management.ManagementScope objwmiservice;
System.Management.ManagementObjectSearcher myObjectSearcher2;
System.Management.ManagementObjectCollection myCollection2;
try
{
objwmiservice = new System.Management.ManagementScope(("\\\\" + (HostOrIP +
"\\root\\cimv2")), myConnectionOptions);
objwmiservice.Connect();
myObjectSearcher2 = new System.Management.ManagementObjectSearcher(objwmiservice.Path.ToString(),
"Select UserName from Win32_ComputerSystem");
myObjectSearcher2.Options.Timeout = new TimeSpan(0, 0, 0, 0, 7000);
myCollection2 = myObjectSearcher2.Get();
GUFlag = false;
foreach (System.Management.ManagementObject myObject in myCollection2)
{
if (!(myObject.GetPropertyValue("Username") == null))
{
string Userx = myObject.GetPropertyValue("Username").ToString();
int posx = Userx.LastIndexOf("\\");
if ((posx > 0))
{
Userx = Userx.Substring((posx + 1));
return Userx.ToUpper();
}
}
}
return "<Nobody>";
}
catch (Exception)
{
return "<Nobody>";
}
finally {
GUFlag = false;
}
}
But the problem is some time deadlock occur on myObjectSearcher2.Get();
Is there any way available to get login username
did you try that?
Environment.UserName
it will give you the user name of the user currently login on windows
EDIT
I found this bit of code here http://www.debugging.com/bug/20243, it may solve your issue.
solution by using WMI ( http://msdn.microsoft.com/en-us/library/system.management.aspx ):
private string GetUserName()
{
string result = "";
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT UserName, Name FROM Win32_ComputerSystem"))
{
foreach (ManagementObject mo in searcher.Get())
{
if (mo["UserName"] != null)
result = mo["UserName"].ToString();
if (mo["Name"] != null)
result += " (" + mo["Name"].ToString() + ")";
}
}
return result;
}
Unless I'm not understanding you correctly, I believe it's just:
using System.Security.Principal;
this.nametext = WindowsIdentity.GetCurrent().Name;
I create a project that check the sub domain and redirect to the exist subdomain ( username ) but I can't find out why when the username is in database it can't show it .
on local system it works finely .. but when I upload it on server it not works .. of course I change the commented place to uncomment for test .. but it's not working ..
it shows this error :
Object reference not set to an instance of an object.
My code is this in page load :
//Uri MyUrl = new Uri(Request.Url.ToString());
//string Url = MyUrl.Host.ToString();
Uri MyUrl = new Uri("http://Subdomain.Mydomain.com/");
string Url = MyUrl.Host.ToString();
string St1 = Url.Split('.')[0];
if ((St1.ToLower() == "Mydomain") || (St1.ToLower() == "Mydomain"))
{
Response.Redirect("Intro.aspx");
}
else if (St1.ToLower() == "www")
{
string St2 = Url.Split('.')[1];
if ((St2.ToLower() == "Mydomain") || (St2.ToLower() == "Mydomain"))
{
Response.Redirect("Intro.aspx");
}
else
{
object Blogger = ClsPublic.GetBlogger(St2);
if (Blogger != null)
{
lblBloger.Text = Blogger.ToString();
if (Request.QueryString["id"] != null)
{
GvImage.DataSourceID = "SqlDataSourceImageId";
GvComments.DataSourceID = "SqlDataSourceCommentsId";
this.BindItemsList();
GetSubComments();
}
else
{
SqlConnection scn = new SqlConnection(ClsPublic.GetConnectionString());
SqlCommand scm = new SqlCommand("SELECT TOP (1) fId FROM tblImages WHERE (fxAccepted = 1) AND (fBloging = 1) AND (fxSender = #fxSender) ORDER BY fId DESC", scn);
scm.Parameters.AddWithValue("#fxSender", lblBloger.Text);
scn.Open();
lblLastNo.Text = scm.ExecuteScalar().ToString();
scn.Close();
GvImage.DataSourceID = "SqlDataSourceLastImage";
GvComments.DataSourceID = "SqlDataSourceCommentsWId";
this.BindItemsList();
GetSubComments();
}
if (Session["User"] != null)
{
MultiViewCommenting.ActiveViewIndex = 0;
}
else
{
MultiViewCommenting.ActiveViewIndex = 1;
}
}
else
{
Response.Redirect("Intro.aspx");
}
}
}
else
{
object Blogger = ClsPublic.GetBlogger(St1);
if (Blogger != null)
{
lblBloger.Text = Blogger.ToString();
if (Request.QueryString["id"] != null)
{
GvImage.DataSourceID = "SqlDataSourceImageId";
GvComments.DataSourceID = "SqlDataSourceCommentsId";
this.BindItemsList();
GetSubComments();
}
else
{
SqlConnection scn = new SqlConnection(ClsPublic.GetConnectionString());
SqlCommand scm = new SqlCommand("SELECT TOP (1) fId FROM tblImages WHERE (fxAccepted = 1) AND (fBloging = 1) AND (fxSender = #fxSender) ORDER BY fId DESC", scn);
scm.Parameters.AddWithValue("#fxSender", lblBloger.Text);
scn.Open();
lblLastNo.Text = scm.ExecuteScalar().ToString();
scn.Close();
GvImage.DataSourceID = "SqlDataSourceLastImage";
GvComments.DataSourceID = "SqlDataSourceCommentsWId";
this.BindItemsList();
GetSubComments();
}
if (Session["User"] != null)
{
MultiViewCommenting.ActiveViewIndex = 0;
}
else
{
MultiViewCommenting.ActiveViewIndex = 1;
}
}
else
{
Response.Redirect("Intro.aspx");
}
}
and my class :
public static object GetBlogger(string User)
{
SqlConnection scn = new SqlConnection(ClsPublic.GetConnectionString());
SqlCommand scm = new SqlCommand("SELECT fUsername FROM tblMembers WHERE fUsername = #fUsername", scn);
scm.Parameters.AddWithValue("#fUsername", User);
scn.Open();
object Blogger = scm.ExecuteScalar();
if (Blogger != null)
{
SqlCommand sccm = new SqlCommand("SELECT COUNT(fId) AS Exp1 FROM tblImages WHERE (fxSender = #fxSender) AND (fxAccepted = 1)", scn);
sccm.Parameters.AddWithValue("fxSender", Blogger);
object HasQuty = sccm.ExecuteScalar();
scn.Close();
if (HasQuty != null)
{
int Count = Int32.Parse(HasQuty.ToString());
if (Count < 10)
{
Blogger = null;
}
}
}
return Blogger;
}
Which place if my code has problem ?
If it works fine locally, I guess the URL in the server has something to do with it.
Were you able to pinpoint exactly where you get the "Object reference not set to an instance of an object." exception? It would help to find the problem.
Anyway check this SO question where its mentioned that Request.Url.ToString() might behave differently in certain situations (Check the accepted answer) →
Request.Url.ToString() returns the machine name nested of the domain