ASP.NET Site Redirection help - c#

I am following the code over here https://web.archive.org/web/20211020203216/https://www.4guysfromrolla.com/articles/072810-1.aspx
to redirect http://somesite.com to http://www.somesite.com
protected void Application_BeginRequest(object sender, EventArgs e)
{
if (Request.Url.Authority.StartsWith("www"))
return;
var url = string.Format("{0}://www.{1}{2}",
Request.Url.Scheme,
Request.Url.Authority,
Request.Url.PathAndQuery);
Response.RedirectPermanent(url, true);
}
How can I use this code to handle situations where http://abc.somesite.com should redirect to www.somesite.com

I'd suggest the best way to handle this would be in the dns record, if you have control of it.

If you don't know what the values will be ahead of time, you can use substring with indexof for the Url path to parse out the value you want and replace it.
If you do know what it is ahead of time, you can always just do Request.Url.PathAndQuery.Replace("abc", "www");
You can also do a dns check as #aceinthehole suggested after you have parsed what you need to make sure you haven't made any mistakes.
assuming you have a string like http://abc.site.com and you want to turn abc into www then you could do something like.
string pieceToReplace = Request.Url.PathAndQuery.substring(0, Request.Url.PathAndQuery.IndexOf(".") + 1);
//here I use the scheme and entire url to make sure we don't accidentally replace an "abc" that belongs later in the url like in a word "GHEabc.com" or something.
string newUrl = Request.Url.ToString().Replace(Request.Url.Scheme + "://" + pieceToReplace, Request.Url.Scheme + "://www");
Response.Redirect(newUrl);
p.s. I don't remember if the Request.Url.Scheme already has the "://" in it or not so you will need to edit accordingly.

I don't think you can do it without access to the DNS. It sounds like you need a wildcard DNS entry:
http://en.wikipedia.org/wiki/Wildcard_DNS_record
Along with IIS configured without host headers (IP only). Then you can use code similar to the above to do what you want.
if (!Request.Url.Host.StartsWith ("www") && !Request.Url.IsLoopback)
Response.Redirect('www.somesite.com');
Perhaps tighten it up some to prevent wwww.somesite.com from getting through. Anything that starts with www including wwwmonkeys.somesite.com would get through the above check. It is just an example.
asp.net mvc: How to redirect a non www to www and vice versa

Related

How to manipulate a url to access a parent directory

I have an asp.net web application that is being hosted on an internal network. In my testing environment of course it gets hosted out on localhost:01010/Views/page.aspx. now whenever I take it live the Url changes to server_name/folder 1/folder 2/views/page.aspx. what I am trying to do is get a new page to open up as server_name/folder 1/folder 2/Uploaded_Images/randomimage.png. Now I Can get the url, but as soon as I do a single ".Remove(url.lastindexof("/")+1)" it returns "server_name/folder 1/folder 2/Views". The I perform my second ".Remove(url.lastindexof("/")+1)"
and the it only returns "server_name/". I am ripping my hair out at this one and am hoping somewhere in the world a .net developer already has this built in. Appreciate all the help.
Also just to specify this is webforms and not mvc. also there is no ajax or page manipulation going on except for a response.write to open the new page.
You don't need the +1, this works:
var url = "server_name/folder 1/folder 2/views/page.aspx";
url = url.Remove(url.LastIndexOf("/"));
url = url.Remove(url.LastIndexOf("/"));
Or you could do it like this:
var parts = url.Split('/');
var newPath = string.Join("/", parts.Take(3));
I assume you are talking about URL's used as links to parts of your site and not physical paths on the file system.
In most cases, you should be able to use methods that construct paths on the fly. For example, in any of your .aspx files (or .aspx.cs files), you can use the ResolveUrl method, like this:
Some link
If there are any places where you need the full URL including the domain (like for email notifications or something like that) then what I have done is keep a static variable accessible to my whole application that gets set the first time Application_BeginRequest runs:
void Application_BeginRequest(object sender, EventArgs e) {
if (SiteRoot == null) {
SiteRoot = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) +
(VirtualPathUtility.ToAbsolute("~") == "/" ? "" : VirtualPathUtility.ToAbsolute("~"));
}
}
That will pull the full URL from the Request details (the URL that the user used to access your site), without any trailing slash.

Routing: how do I redirect to a url when a parameter is missing?

I have routes like this:
example.com/{category}/articles.
There isn't a route for
example.com/{category}
example.com/
I want to redirect all that traffic to
example.com/{category}/articles with a default value.
I've read that I can use default values with a RouteValueDictionary:
routes.MapPageRoute("ArticlesAll", "{category}/articles/", "~/ArticlesPage.aspx", false, new RouteValueDictionary { { "category", "cats" } });
But that doesn't do any redirecting.
Would I need another route to forward to the one above or is there a more efficient way of doing this?
What you are asking is a bit unclear, but let me offer what I usually do.
If you are trying to make it so that two similar links can be written, for example www.example.com/read/penguin/article/ and www.example.com/read/panda/article. I would just write the whole string / URL with a variable in the middle:
private string destination = "penguin";
private string url = "www.example.com/read/" + destination + "/article/";
void Test () {
destination = "lion";
text.URL = url;
}
Sorry, I may have made gramatical mistakes in my code, but I hope you get the point. I may have completely misunderstood you though, so clarification would be appreciated.
You can setup these two routes:
routes.MapPageRoute("ArticlesAll", "{category}/articles/{*value}", "~/ArticlesPage.aspx");
routes.MapPageRoute("CatchAll", "{*value}", "~/ArticlesPage.aspx");
to catch anything and redirect to your desired page. I just assumed where you want to lead your users, change the aspx part as needed. Keep in mind that you can use {value} to access the whatever the user wrote.
For example if they wanted to navigate to dogs and you wanted to redirect to dogs/articles/ArticlesPage.aspx, you should use:
routes.MapPageRoute("CatchAll", "{*value}", "~/{value}/articles/ArticlesPage.aspx");
EDIT
If you want to actually redirect to the new URL and not just serve up the right page, you can use the CatchAll route to redirect to a page (say Redirect.aspx) that's sole purpose is to parse data from the RouteData object, construct the new URL and Redirect.

Getting full URL from URL with tilde(~) sign

I am trying to get a typical asp.net url starting with the tilde sign ('~') to parse into a full exact url starting with "http:"
I have this string "~/PageB.aspx"
And i want to make it become "http://myServer.com/PageB.aspx"
I know there is several methods to parse urls and get different paths of server and application and such. I have tried several but not gotten the result i want.
Try out
System.Web.VirtualPathUtility.ToAbsolute("yourRelativePath");
There are various ways that are available in ASP.NET that we can use to resolve relative paths to a resource on the server-side and making it available on the client-side. I know of 4 ways -
1) Request.ApplicationPath
2) System.Web.VirtualPathUtility
3) Page.ResolveUrl
4) Page.ResolveClientUrl
Good article : Different approaches for resolving URLs in ASP.NET
If you're in a page handler you could always use the ResolveUrl method to convert the relative path to a server specific path. But if you want the "http://www.yourserver.se" part aswell, you'll have to prepend the Request.Url.Scheme and Request.Url.Authority to it.
string.Format("http://{0}{1}", Request.Url.Host, Page.ResolveUrl(relativeUrl));
This method looks the nicest to me. No string manipulation, it can tolerate both relative or absolute URLs as input, and it uses the exact same scheme, authority, port, and root path as whatever the current request is using:
private Uri GetAbsoluteUri(string redirectUrl)
{
var redirectUri = new Uri(redirectUrl, UriKind.RelativeOrAbsolute);
if (!redirectUri.IsAbsoluteUri)
{
redirectUri = new Uri(new Uri(Request.Url.GetLeftPart(UriPartial.Authority) + Request.ApplicationPath), redirectUri);
}
return redirectUri;
}

How to short a URL

I have a URL like:
www.zzz.com/ExternalDocuments/ExternalDocumentUpload.aspx?hjgbasdjfjsggfsdf
I want to provide something short for ExternalDocuments/ExternalDocumentUpload.aspx. I don't want to shorten the whole url.
It sounds like what you want isn't "shortening" -- where a service like e.g. bit.ly is used to shorten the entire URL for use in Twitter or suchlike -- but "URL rewriting".
This takes a "friendly" path provided by the user -- to the right of the "/" -- and turns it into the URL you need for ASP.NET to find the page.
There's a few different ways to do this depending on precisely which flavour of ASP.NET and IIS you're using. ScottGu has a good roundup here:
http://weblogs.asp.net/scottgu/archive/2007/02/26/tip-trick-url-rewriting-with-asp-net.aspx
and for IIS7 I've used the one here:
http://www.iis.net/download/URLRewrite
You can set up url rewriting in global.asax file, on Application_BeginRequest event, that would run on every request, checking requested url and, if needed, redirecting it to desired url. You can make the checking like this:
protected void Application_BeginRequest(Object sender, EventArgs e)
{
if (Request.RawUrl== "/someShorturl/page.aspx")
{
HttpContext.Current.RewritePath("/ExternalDocuments/ExternalDocumentUpload.aspx?hjgbasdjfjsggfsdf");
}
}
So, if user goes to "www.zzz.com/someShorturl/page.aspx", he will get "www.zzz.com/ExternalDocuments/ExternalDocumentUpload.aspx?hjgbasdjfjsggfsdf" page, although url in the browser won't change.
If you'd like to change shortened url into long original url, you can call Response.Redirect instead the RewritePath method.
This example is for one speciffic url, but you can create more complex logic, of course.

ReportViewer "Missing URL parameter: Name"

In a web application I'm working on the ReportViewer keeps giving me a error "Missing URL parameter: Name". I have found the cause but not a solution.
The url that is causing the exception from the report viewer
Reserved.ReportViewerWebControl.axd?ReportSession=3bkunv2wte3wmnabkquyr1y0&ControlID=1e2b5870e07b46abac7fd32a9e0e4b9d&Culture=1033&UICulture=1033&ReportStack=1&OpType=ReportArea&Controller=ctl00_ASPxRoundPanel3_PageContent_Wizard1_ReportViewer1&PageNumber=1&ZoomMode=Percent&ZoomPct=100&ReloadDocMap=true&SearchStartPage=0&LinkTarget=_top
if you notice in the query string instead of "&name=" for some reason it becomes "&amp ;Name=".
I noticed on numinous google searches there seams to be a lot of people having the same problem but not one solution.
Sounds like something is mangling your URL somewhere. Do you by chance have a Bluecoat proxy in place? I saw something about Bluecoat mangling the URL.
If that's the case and you have control over the proxy, you might be able to get a tunnel punched through it for your reports. Otherwise, you might have to rewrite the URL on your end.
Check here for more information (last post in the thread has a possible workaround).
You can fix this globally by checking for the BlueCoat request header at the start of each request. This bit of code placed in global.asax.cs fixes the problem:
protected void Application_BeginRequest(Object sender, EventArgs e)
{
// Fix incorrect URL encoding by buggy BlueCoat proxy servers:
if (!String.IsNullOrEmpty(Request.ServerVariables["HTTP_X_BLUECOAT_VIA"]))
{
string original = Request.QueryString.ToString();
if (original.Contains(Server.UrlEncode("amp;")))
{
HttpContext.Current.RewritePath(Request.Path + "?" + original.Replace(Server.UrlEncode("amp;"), "&"));
}
}
}
I'm not sure if any other proxy servers have the same issue, but if they do, this could be easily be adapted to check for the presence of & in the QueryString instead of checking for the BlueCoat header (or I guess, you could just check for the headers of any other affected products, which might be safer.

Categories