Response.Redirect using ~ Path - c#

I have a method that where I want to redirect the user back to a login page located at the root of my web application.
I'm using the following code:
Response.Redirect("~/Login.aspx?ReturnPath=" + Request.Url.ToString());
This doesn't work though. My assumption was that ASP.NET would automatically resolve the URL into the correct path. Normally, I would just use
Response.Redirect("../Login.aspx?ReturnPath=" + Request.Url.ToString());
but this code is on a master page, and can be executed from any folder level. How do I get around this issue?

I think you need to drop the "~/" and replace it with just "/", I believe / is the root
STOP RIGHT THERE! :-) unless you want to hardcode your web app so that it can only be installed at the root of a web site.
"~/" is the correct thing to use, but the reason that your original code didn't work as expected is that ResolveUrl (which is used internally by Redirect) tries to first work out if the path you are passing it is an absolute URL (e.g. "**http://server/**foo/bar.htm" as opposed to "foo/bar.htm") - but unfortunately it does this by simply looking for a colon character ':' in the URL you give it. But in this case it finds a colon in the URL you give in the ReturnPath query string value, which fools it - therefore your '~/' doesn't get resolved.
The fix is that you should be URL-encoding the ReturnPath value which escapes the problematic ':' along with any other special characters.
Response.Redirect("~/Login.aspx?ReturnPath=" + Server.UrlEncode(Request.Url.ToString()));
Additionally, I recommend that you (or anyone) never use Uri.ToString - because it gives a human-readable, more "friendly" version of the URL - not a necessarily correct one (it unescapes things). Instead use Uri.AbsoluteUri - like so:
Response.Redirect("~/Login.aspx?ReturnPath=" + Server.UrlEncode(Request.Url.AbsoluteUri));

you can resolve the URL first
Response.Redirect("~/Login.aspx);
and add the parameters after it got resolved.

What about using
Response.Redirect(String.Format("http://{0}/Login.aspx?ReturnPath={1}", Request.ServerVariables["SERVER_NAME"], Request.Url.ToString()));

Related

Question Mark in Querystring with Server.MapPath returning an error

I am working on a web application. Here I am storing attachments/uploads on server physical directory. The parent folder of uploads may contain special characters like '?'
Example of URL
"~/ChapterFiles/Capgeminisdfsdf_BE CSE ?_CoverPic/CoverPic.jpg"
When I am doing, Server.MapPath() on this URL, I am getting an error "Illegal characters in path."
Can't remove question mark from folder name as it's part of requirement. Please suggest a solution, I need to fix it urgently.
You can use something like:
String absoluteDir = Server.MapPath("~");
String myRelativePath = "~/ChapterFiles/Capgeminisdfsdf_BE CSE ? _CoverPic/CoverPic.jpg".Replace("/","\\");
String absolutePath = Path.Combine(absoluteDir,myRelativePath);
It will work. I advice you to write some unit tests for this function.
Use HttpServerUtility.UrlEncode and UrlDecode to encode/decode the string.
Question marks are not allowed in folder names in Windows. Your requirement in it's current form is impossible to implement and there is no "fix". You need to rethink how to map URL's to folder and file names.
You need to use # sign before the string. Like below
#"~/ChapterFiles/Capgeminisdfsdf_BE CSE ?_CoverPic/CoverPic.jpg"
Reference link

ASP.NET Page Routing - URL Parameters stripped from target resource

ASP.NET c# project... trying to do a very simple page route.
Please note that I know this is NOT actually doing any dynamic routing... I have the id hard coded like this for a reason.
Example:
RouteTable.Routes.MapPageRoute("Test", "ABC", "~/Test.aspx?id=101");
I can browse to http://www.mysite.com/ABC no problems, the page Test.aspx loads, the routing is working as expected.
BUT... where has my id=101 gone?
Request.QueryString["id"] \\ is null...
Page.RouteData.Values["id"] \\ is null...
How can I get hold of the hard coded id in my target resource for the routing?
I got it working by passing DataTokens.
In my real world scenario I don't know what the URL parameters will be (there could be just the "id" like in my question... or there could be others, sometimes none), so I have to do the following:
First check to see if there is a "?" character in the routing target... if there is, then:
Run the string after the "?" character through HttpUtility.ParseQueryString
Then, loop through that collection and add them to a System.Web.Routing.RouteValueDictionary
Then finally add the route, with the DataTokens property set to the RouteValueDictionary

URL getting Appended when using Response.Redirect

I have a URL say /Registration/GetName.aspx/?language=English
When i click on a Asp.net Button on the same Page and say Response.Redirect("CheckLoginName.aspx");
It gives me a weird URL
/Registration/GetName.aspx/CheckLoginName.aspx
What should i do
Please Help?
You should use "~/" inside your Redirect
So your code will look something like this
Response.Redirect("~/CheckLoginName.aspx");
Hope this helps
You should remove the trailing / before the query string, since it serves no purpose. Your URL should be /Registration/GetName.aspx?language=English. Another option is to have Response.Redirect("../CheckLoginName.aspx"); This should also work.
I think a solution using a relative path is better, since it is location independant. If you move these two files to another URL, there will be no need for code changes.

What's the quickest, cleanest way to remove parent pathing from a URL string?

In C#, is there any built-in way to "correct" URLs that have parent pathing in them? So, I want to take this:
/foo/bar/../baz.html
And turn it into...
/foo/baz.html
(The "bar" directory being negated by the ".." after it in the path.)
I've tried to hand-roll this, but the logic gets pretty ugly, pretty quickly. Consider something like:
/foo1/foo2/../foo3/foo4/foo5/../../bar.html
The path I headed down was to move through the URL, segment by segment, and start writing a new URL. I would only include segment 1 in the new URL, if segment 2 wasn't "..". But, in the case above, I need to "look ahead" and figure out how many parent paths I have coming.
I tried to use Path.GetFullPath, and it technically got it work, but, man, it's ugly. Fair warning: you may want to avert your eyes on this one:
Path.GetFullPath(myUrl).Replace(Path.GetFullPath(#"\"), "").Replace(#"\", "/") + "/";
GetFullPath returns a file system path from the "C:\" root, so you essentially have to replace that too, than convert the slashes, etc.
I can probably bang this out eventually (and my ugly code above technically works), but it strikes me that I can't be the first one to try this. Google did not help.
(The answer in another language would be helpful too -- at least it would show the logic.)
This should work for all URLs (including URLs with a QueryString):
var url = "/foo/bar/../bar.html";
var ubuilder = new UriBuilder();
ubuilder.Path = url;
var newURL = ubuilder.Uri.LocalPath;
Try the VirtualPathUtility class. It has some methods that should be able to help here, specifically the ToAbsolute() method, which if memory doesn't fail me, should be able to take an application-relative path and convert it to an application absolute path.
If you really want to roll your own version, try using a stack:
split path by path separator '/'
loop through segments
push any segment that is not '..' onto a stack
if the segment is '..', pop the stack
join the segments with the path separator '/'
But as others have noted: It is probably better to get your library to do this for you.

Remove anchor from URL in C#

I'm trying to pull in an src value from an XML document, and in one that I'm testing it with, the src is:
<content src="content/Orwell - 1984 - 0451524934_split_2.html#calibre_chapter_2"/>
That creates a problem when trying to open the file. I'm not sure what that #(stuff) suffix is called, so I had no luck searching for an answer. I'd just like a simple way to remove it if possible. I suppose I could write a function to search for a # and remove anything after, but that would break if the filename contained a # symbol (or can a file even have that symbol?)
Thanks!
If you had the src in a string you could use
srcstring.Substring(0,srcstring.LastIndexOf("#"));
Which would return the src without the #. If the values you are retreiving are all web urls then this should work, the # is a bookmark in a url that takes you to a specific part of the page.
You should be OK assuming that URLs won't contain a "#"
The character "#" is unsafe and should
always be encoded because it is used in World Wide Web and in other
systems to delimit a URL from a fragment/anchor identifier that might
follow it.
Source (search for "#" or "unsafe").
Therefore just use String.Split() with the "#" as the split character. This should give you 2 parts. In the highly unlikely event it gives more, just discard the last one and rejoin the remainder.
From Wikipedia:
# is used in a URL of a webpage or other resource to introduce a "fragment identifier" – an id which defines a position within that resource. For example, in the URL http://en.wikipedia.org/wiki/Number_sign#Other_uses the portion after the # (Other_uses) is the fragment identifier, in this case indicating that the display should be moved to show the tag marked by ... in the HTML
It's not safe to remove de anchor of the url. What I mean is that ajax like sites make use of the anchor to keep track of the context. For example gmail. If you go to http://www.gmail.com/#inbox, you go directly to your inbox, but if you go to http://www.gmail.com/#all, you'll go to all your mail.
The server can give a different response based on the anchor, even if the response is a file.

Categories