URL where user come from ASP.Net but have NULL - c#

I want to know-from what url user come from.
So, i use
Uri MyUrl = Request.UrlReferrer;
But when i get only null value from MyUrl:
I have two projects-first is my aspx page, second- redirects to this first project-page with GET parameters.
But when second project redirect to first project- i have :
Object reference not set to an instance of an object.
My second test project so simple:
protected void Page_Load(object sender, EventArgs e)
{
Response.Redirect("http://localhost:54287/go.aspx?id=DEFAULT");
}
First and main project:
protected void Page_Load(object sender, EventArgs e)
{
//Request.ServerVariables('http_referer');
// Request.ServerVariables;
string id = Request.QueryString["id"];
if (id != null)
{
Uri MyUrl = Request.UrlReferrer;
Console.WriteLine(MyUrl);
Response.Write("Referrer URL : " + MyUrl.AbsolutePath);
}
}
Error in :Response.Write("Referrer URL : " + MyUrl.AbsolutePath);

OK, there a a few errors:
Your code:
Uri MyUrl = Request.UrlReferrer;
Console.WriteLine(MyUrl);
Response.Write("Referrer URL : " + MyUrl.AbsolutePath);
In the code above you get a NullReferenceException because MyUrl is null.
The UrlReferer may be null, so you have to check this like:
Uri MyUrl = Request.UrlReferrer;
Console.WriteLine(MyUrl);
if (MyUrl != null)
Response.Write("Referrer URL : " + MyUrl.AbsolutePath);
Also you can never make sure that the UrlReferer can have a value, if the user comes from another website you don't know if this website will provide this value, so you have first to assume the referrer is null (in summary never trust it).
Second, when you use Response.Redirect on your code ran server-side you don't know what is the referrer.
I find this question and this question that will help you to better understand.

UrlReferrer is based off the HTTP_REFERER header that a browser should send. But, as with all things left up to the client, it's variable.
I know some "security" suites (like Norton's Internet Security) will strip that header, in the belief that it aids tracking user behavior. Also, I'm sure there's some Firefox extensions to do the same thing.
Bottom line is that you shouldn't trust it. Just append the url to the GET string and redirect based off that.
Reference:
Stackover flow reference

Related

Error when pass a directory path

In start page: I want to pass a directory path to a popup window page when client click on LinkButton lbtnEditText
<asp:LinkButton ID="lbtnEditText" runat="server" Text="Edit Text" CommandArgument='<%# Eval("Path") + "," + Eval("Name")%>' OnCommand="Button1_Click"></asp:LinkButton>
And the code behind:
protected void Button1_Click(object sender, CommandEventArgs e)
{
string[] values = e.CommandArgument.ToString().Split(',');
string queryString =
"editpage.aspx?path="
+ values[0];
string newWin =
"window.open('" + queryString + "');";
ClientScript.RegisterStartupScript
(this.GetType(), "pop", newWin, true);
}
The queryString exactly is = "editpage.aspx?path=D:\\C#Projects\\website\\Lecturer\\giangvien\\profile.xml" (I check it when I debug)
But In destination page (popup window): editpage.aspx
string path = Request.QueryString["path"];
string content = File.ReadAllText(path);
if(content!=null)
textarea.Value = content;
It has an error: Could not find file 'D:\C#Projects\website\C
Try to debug, the path I recieved is just only : "D:C"
And in the address bar of editpage.aspx display:
http://localhost:41148/website/editpage.aspx?path=D:C#ProjectswebsiteLecturergiangvienprofile.xml
Help!!! Why is the path changed when I pass it to the editpage???
The reason behind happening so is :: you are passing query string data which is having unexpected characters which are '\,#'.
The solution to this is escape and encode this values before setting as query string values
Encoding Urls correctly is unfortunately required skill for anyone doing web development...
Everything after # is "hash" portion of Url and browser don't need to send it to server. More formal name is fragment identifier.
What you need to do is encode value of path query parameter correctly (i.e. with encodeURIComponent funcition in JavaScript).
To give you the actual solution for C#:
string queryString = "editpage.aspx?path=" + System.Web.HttpUtility.UrlEncode(values[0]);
see reference for encoding http://msdn.microsoft.com/en-us/library/system.web.httputility.urlencode.aspx
and decoding http://msdn.microsoft.com/en-us/library/system.web.httputility.urldecode%28v=vs.110%29.aspx

Write Current URL To String C#

This is what I am trying to do.
Windows Form App loads with web browser
Goes to a certain link
Checks to see if the url bar is empty, if not it takes the current url and writes to a string and then navigates to some other url.
I keep getting Cannot implicitly convert type 'System.Uri' to 'string'
and I have tried a few things but can't get my head around it.
string url;
try
{
if (webBrowser1.Url != null)
{
// url = webBrowser1.Url;
MessageBox.Show("Success!");
}
else
{
MessageBox.Show(":(!");
}
}
catch
{
MessageBox.Show("Something Screwed Up");
}
Now at this point I get :( when I comment out the error. This is on form1.cs - should I be doing this on program.cs? It seems like the object may not be created a the point when I check but I have no idea. By default the form loads with a URL pre-loaded.
webBrowser1.Url is URI object
url is String object
it tells you those are diffrent types and there no implicit convertion
url = webBrowser1.Url.ToString();
see great article:
http://msdn.microsoft.com/en-us/library/ms173105.aspx

When user hit's the site the custom error page is shown. Why? This is to few users and sporadic

Could somebody please help me?
We are developing a asp.net application using asp.net 2.0 framework. The issue is sporadic. As soon as a particular user hits the site in production a custom error page is shown. I been told that this user could get in successfully some times and after some idle time he is getting this error page. We not even not yet log in to site. Just as soon as i hit the site Ex:- www.Mywebsite.com the custom error is dispalyed. Could somebody help me on this. One more thing i have on my local machine .net 3.5 service pack1 installed and in production on only once server the service pack is installed. Could this be the cause of the problem?. some times it is showing the page and some users custom error. They not even visited the login screen yet. As soon as some users hit the site they see the customer error page, instead of login page. As i told this is happening as the user hitting the site I started checking my load code of index.aspx (page set up in virtual directories documents as start up page) and this is the code i am using.
My each .aspx page is inheriting the PageBase class which has the below method overriden and with the below code. If you see carefully the expiration of "langCookie" been given as 30 minutes. Will this be a problem? Below is a little code of my PageBase and my index.aspx. I am not sure what user's are doing. I heard it comes sporadically, so became hard to reproduce. One more thing since this is mix of asp and aspx pages i used below in web.config, Otherwise i am gettinig the sqaure characters in classic asp pages when i open them.
PageBase.cs Code:-
protected override void InitializeCulture()
{
base.InitializeCulture();
HttpCookie langCookie = null;
if (null == Request.Cookies[SESSION_KEY_LANGUAGE])
{
foreach (string s in Request.Cookies)
{
if (HttpUtility.UrlDecode(Request.Cookies[s].Name) == SESSION_KEY_LANGUAGE)
{
langCookie = new HttpCookie(SESSION_KEY_LANGUAGE);
langCookie.Value = HttpUtility.UrlDecode(Request.Cookies[s].Value); langCookie.Expires = DateTime.Now.AddMinutes(30.0);
Response.Cookies.Add(langCookie);
break;
}
}
}
else
{
langCookie = Request.Cookies[SESSION_KEY_LANGUAGE];
}
if (null != langCookie)
{
if (langCookie.Value != "")
{
CultureInfo cultureInfo = new CultureInfo(langCookie.Value);
ApplyNewLanguage(cultureInfo);
}
}
}
index.aspx.cs:- The starting page in virtual is set as index.aspx
protected void Page_Load(object sender, EventArgs e)
{
//Set sign button as default button for login (press enter)
Page.Form.DefaultButton = "ButtonSignIn";
//Get Cookie Language
if (null == Request.Cookies[SESSION_KEY_LANGUAGE])
{
cookie = new HttpCookie(SESSION_KEY_LANGUAGE);
}
else
{
cookie = Request.Cookies[SESSION_KEY_LANGUAGE];
}
if (null == Request.Cookies[SESSION_KEY_LANGUAGE_FORASP])
{
cookieASP = new HttpCookie(SESSION_KEY_LANGUAGE_FORASP);
}
else
{
cookieASP = Request.Cookies[SESSION_KEY_LANGUAGE_FORASP];
}
if (!IsPostBack)
{
//check if chkbtaccess cookies exists
if (null != Request.Cookies[CHECKACCESS])
{
HttpCookie cookieCheckAccess = Request.Cookies[CHECKACCESS];
string strCKBTC = DecryptUsernamePass(cookieCheckAccess.Value.ToString());
if (String.Compare(strCKBTC, string.Empty) != 0)
{
string[] aryCKBTC = strCKBTC.Split(Convert.ToChar(","));
TextBoxUsername.Text = aryCKBTC[0];
TextBoxPassword.Text = aryCKBTC[1];
CheckBoxRememberMe.Checked = true;
}
}
private string DecryptUsernamePassword(string strText)
{
string strDecryptedUsernamePassword = string.Empty;
strDecryptedUsernamePassword = CommonUtil.EncryptDecryptHelper.Decrypt(HttpUtility.UrlDecode(strText, Encoding.Default));
//strDecryptedUsernamePassword = CommonUtil.EncryptDecryptHelper.Decrypt(HttpUtility.UrlDecode(strText, Encoding.Unicode));
return strDecryptedUsernamePassword;
}
private string EncryptUsernamePassword(string strText)
{
string strEncryptedUsernamePassword = string.Empty;
strEncryptedUsernamePassword = HttpUtility.UrlEncode(CommonUtil.EncryptDecryptHelper.Encrypt(strText), Encoding.Default);
//strEncryptedUsernamePassword = HttpUtility.UrlEncode(CommonUtil.EncryptDecryptHelper.Encrypt(strText), Encoding.Unicode);
return strEncryptedUsernamePassword;
}
As a starting point, you should add some logging and exception handling in this code so that you can narrow down what the error could be. It would also make your code more robust and tolerant to invalid cookie values.
An easy way to do this would be to implement the error handler in Global.asax:
protected void Application_Error(Object sender, EventArgs e)
{
Exception exception = Server.GetLastError();
}
This should give you the exception that occurred, which you can then examine (eg. in the debugger, log it to a file, etc...) to see what is causing the error.
For a temporary measure, you could turn off custom errors in web.config:
<customErrors mode="Off"/>
This will enable you to see the exception in your web browser when it occurs. I wouldn't recommend that you use that setting on a live site though.

Good ASP.NET method for checking, reading and returning file contents

I found a good way to check if a file exists and read the contents if it does, but for some reason I can't create a method out of it.
Here's what I have so far:
<script runat="server">
void Page_Load(Object s, EventArgs e) {
lblFunction.Text = mwbInclude("test.txt");
}
string mwbInclude(string fileName) {
string inc = Server.MapPath("/extra/include/" + Request["game"] + "/" + fileName);
string valinc;
if(System.IO.File.Exists(inc))
{
valinc = System.IO.File.ReadAllText(inc);
}
return valinc;
}
</script>
I wish I could provide more info, but the server this is on doesn't show any feedback on errors, just a 404 page.
I think
valinc = Response.Write(System.IO.File.ReadAllText(inc));
should be
valinc = System.IO.File.ReadAllText(inc);
Why are you setting the Text property and calling Response.Write? Do you want to render the text as a label, or as the whole response?
If you're getting a 404, it's because your page isn't being found, not because there's a problem with the script itself. Have you tried ripping out all of the code and just sticking in some HTML tags as a sanity check?

Why are backward slashes removed from querystring - ASP.NET & Javascript

I am trying to generate a URL that contains a UNC path as one of the query string variables. The URL will open in a pop up window when an ASP.NET button control is clicked by the user. When the clicks the button, the backwards slashes are removed from the UNC path causing the page to break.
The button renders correctly in the page source file with all the backward slashes.
Is there any way to prevent this?
Here is my source code:
Code behind:
string unc = #"\\myserver\myfolder\myfile.txt";
string url = string.Format("http://www.mysite.com/page.aspx?a={0}", unc);
MyButton.Attributes.Add("onclick", #"javascript:FullPop('" + url + #"')");
ASPX page
<script language="javascript" type="text\javascript">
function FullPop(Newurl) {
Win = window.open( Newurl,"Monitor", "fullscreen=0,toolbar=1,location=1,directories=1,status=1,menubar=1,scrollbars=1,resizable=1,width=800,height=600,top=50,left=50");
Win.focus();
}
</script>
<asp:button id="MyButton" runat="server" cssclass="mycss" text="View Actual Target" />
Update
Server.UrlEncode does not work. Same behavior.
Update 1
Based on Daniel Lew's answer, I developed the following solution:
protected void Page_Load(object sender, EventArgs e)
{
string unc = #"\\myserver\myfolder\myfile.txt";
string url = string.Format("http://www.mysite.com/page.aspx?a={0}", unc);
MyButton.Attributes.Add("onclick", #"javascript:FullPop('" + this.EscapeforJavaScript(url) + #"')");
}
private string EscapeforJavaScript(string url)
{
return url.Replace(#"\", #"\\");
}
You have to URL encode the value that you put in the URL:
string url = "http://www.mysite.com/page.aspx?a=" + Server.UrlEncode(unc);
Edit:
To safely put the url in the Javascript code, you also have to encode the string for being a literal string:
MyButton.Attributes.Add("onclick", #"FullPop('" + url.Replace(#"\", #"\\").Replace("'", #"\'") + #"')");
(The javascript: protocol is only used when the Javascript is used as href for a link, not when you put code in an event like onclick.)
I don't know anything about asp.net, but I have had experience with problems when adding text straight into JavaScript before through templating. Have you tried escaping the backslashes on your url, to avoid this?
// Returns "\myservermyfoldermyfile.txt", due to escpaing the backslash.
alert("\\myserver\myfolder\myfile.txt");
// Returns correct value of "\\myserver\myfolder\myfile.txt"
alert("\\\\myserver\\myfolder\\myfile.txt");
You may want to try URLEncoding your string on your server side, using the following method:
public static string UrlFullEncode(string strUrl)
{
if (strUrl == null)
return "";
strUrl = System.Web.HttpUtility.UrlEncode(strUrl);
}
I'm not 100% sure it if will replace the backslashes, but it's worth a try.

Categories