ASP.NET: Tracking dynamic subdomaiins - asp.net

My company wants to mail out postcards asking the recipient to visit a website for add'l information. The url on the postcard will contain a unique subdomain, for tracking purposes.
So for example, John Smith's url will look like johnsmith.mysite.com. Amy Johnson's postcard url will be amyjohnson.mysite.com, etc.
So, 2 questions. One, can url's be setup in this fashion? We would be sending thousands of unique postcards, so manually setting up subdomain's on our web host's admin section isn't realistic. And two, how in asp.net, could I capture just the subdomain?
Thanks

I took an alternate approach to resolving my problem. Instead of trying to handle this entirely programatically, I created a "wildcard DNS" on my domain with my web host (GoDaddy). There's some info for it at this link.
Once my domain was setup to allow wildcard subdomains, I was able to go into my code, and use the following, which allows me to extract the name of the subdomain:
Uri url = new Uri(System.Web.HttpContext.Current.Request.Url.AbsoluteUri);
string subDomain = GetSubDomain(url);
And...
public string GetSubDomain(Uri url)
{
if (url.HostNameType == UriHostNameType.Dns)
{
var host = url.Host;
if (host.Split('.').Length > 2)
{
var lastIndex = host.LastIndexOf(".");
var index = host.LastIndexOf(".", lastIndex - 1);
return host.Substring(0, index);
}
}
return null;
}

Related

RouteCollection Querysting

I am trying to define MapPageRoute on the application global.asax but my problem is that I can not route the specific URL to a physical file with a query string.
For example I want to redirect http://mysite.com/Apple to http://mysite.com/product.aspx?id=95.
What I managed to achieve so far is if a user ask for ./Apple he will be redirected to ./product.aspx but I can not pass the query string.
Looking forward for your comments.
Try this:
if (Page.RouteData.Values["Apple"] != null)
{
int appleID = Convert.ToInt32(Page.RouteData.Values["Apple"]);
Response.Redirect("~/product.aspx?id=" + appleID.ToString(), true);
}

SEO URL rewriting ASP.NET

I already have an ASP.NET Web Site
I want to change my site to be more SEO url friendly.
I want to change ex. this site:
www.mydomain.aspx?articleID=5
to:
www.mydomain/article/learningURLrewrite
- articlename needs to be read from DB
How do I accomplish this?
I have already tried with some articles from Google which mentions IhttpModule without any luck.
My goal is to have a class responsible for redirecting based on folderpath(like this):
string folderpath = "my folderpath" (could be articles, products etc.)
string id = Request.QueryString["id"].ToString();
if(folderpath.equals("articles"))
{
string name = //find name from id in DB
//redirect user to www.mydomain/article/name
}
if(folderpath.equals("products"))
{
string name = //find name from id in DB
//redirect user to www.mydomain/products/name
}
Also I want to remove the aspx extension
You can use routing with ASP.NET WebForms too.
The steps are:
Add the route (or routes) at application start.
//In Global.asax
void Application_Start(object sender, EventArgs e)
{
RouteTable.Routes.MapPageRoute("My Routename", "{*name}", "~/Article.aspx");
}
Create the Article.aspx as a normal webform
In the code for Article.aspx, you can access the url path like this:
public void Page_Load(object sender, EventArgs e)
{
var thePath = RouteData.Values["name"];
// Lookup the path in the database...
}
This posting tells you exactly how to use asp.net 4's routing engine - give it a whirl - if you have a specific problem in implementing it let us know.
http://weblogs.asp.net/dotnetstories/archive/2011/01/03/routing-in-asp-net-4-0-web-forms.aspx
Since you need specific parameter usage, you can define the parameters to get sent to your page. For that see:
http://msdn.microsoft.com/en-us/library/cc668177.aspx
and
How to: Access URL Parameters in a Routed Page
If you are using ASP.NET 4, then you should look into URL Routing. You would end up setting up custom routes like so:
routes.MapPageRoute(
"View Article", // Route name
"Articles/{*ArticleName}", // Route URL
"~/Articles.aspx" // Web page to handle route
);
And you write out the new links like so:
Page.GetRouteUrl("View Article", new { ArticleName= NAMEFROMDATABASE });
Unfortunately I won't give you a summary of how to build your entire site, but 2 really good places to start are an article by Scott Gu, and one on 4 Guys.
If you are using .net 3.5 or less then you can use these
http://urlrewriting.net
http://urlrewriter.net
I use the second one, in all my projects made in .net 3.5
if using .net 4.0 then you can do these
URL routing ( I think it does not support sub domain rewriting)
URL Rewrite 2.0 ( works with IIS 7 only)
UPDATE
Add these lines below the appSettings tag
<rewriter configSource="URLRewriter.config"/>
Then create separate file named as URLRewriter.config
And in that you can write like this (Add processing stop for the files not to be rewritten i.e images and js, etc)
<rewrite url="^(/.+(\.gif|\.png|\.jpg|\.ico|\.pdf|\.css|\.js|\.flv|\.eot|\.svg|\.ttf|\.woff|\.txt|\.doc|\.docx|\.pdf|\.xls|\.xlsx|\.xml)(\?.+)?)$" to="$1" processing="stop" />
<rewrite url="~/article/([^/.]+)" to="~/articledetail.aspx?articlename=$1" />
Then you would get the article name in the query string like this
string articlename = Request.QueryString["articlename"];
And the menu or other location of the site where you want to put the link to article, you can add an the AppSettings so that later on if you want to change the url pattern you can change it easily from the configs only,
<add key ="ArticalDetailsURL" value="/article/{0}" />
Then, in the page you can do like this
string articleName = "TestArticle";
lnkMenuLink.NavigateUrl = string.Format(ConfigurationSettings.AppSettings["ArticalDetailsURL"], articleName);
Thanks and Regards,
Harsh Baid

Asp.net 4 url rewrite a subdomain as a folder

What I'm trying to do is the following, I want to rewrite this kind of url:
blog.domain.com/...
into
domain.com/blog/...
It's in a shared host environment, using IIS7/ASP.Net 4. Another thing is that both the domain and the blog subdomain have different aps running. I've been searching for hours for what's the best solution here, and I hope someone can guide me a bit here. Thanks!
Here is an attempt as first idea.
// keep a valid list somewhere
List<string> cValidNames = new List<string>();
cValidNames.Add("blog");
// get the host
//string TheHost = Request.Url.Host;
string TheHost = "blog.domain.com";
// find the first part, assume that the domain is standard and not change
int WhereStarts = TheHost.IndexOf(".domain.com");
// if we found it
if(WhereStarts != -1)
{
string cTheFirstPart = TheHost.Substring(0, WhereStarts);
// if its on the valid domain (exclude the www)
if (cValidNames.Contains(cTheFirstPart))
{
// now I add in the frond the name and continue with the rest url
string cFinalPath = "/" + cTheFirstPart + Request.RawUrl;
// now rewrite it.
HttpContext.Current.RewritePath(cFinalPath, false);
return;
}
}

SEO: Duplicated URLs with and without dash "/" and ASP.NET MVC

after reading this article "Slash or not to slash" (link: http://googlewebmastercentral.blogspot.com/2010/04/to-slash-or-not-to-slash.html) on Google Webmaster Central Blog (the oficial one) I decided to test my ASP.NET MVC app.
For example:
http://domain.com/products and http://domain.com/products/ (with "/" in the end), return the code 200, which means: Google understands it as two different links and likely to be a "duplicated content". They suggest to choose the way you want... with or without dash and create a 301 permanent redirect to the preferred way.
So if I choose without dash, when I try to access http://domain.com/products/ it will return a 301 to the link without dash: http://domain.com/products.
The question is, how can I do that with ASP.NET MVC?
Thanks,
Gui
If your using IIS 7 you could use the URL Rewrite Extension ScottGu has a blog post about it here.
Alternatively if you want to do it in code you could inherit from PerRequestTask. Here some sample code the removes the www from an address - this is from Shrinkr:
public class RemoveWww : PerRequestTask
{
protected override TaskContinuation ExecuteCore(PerRequestExecutionContext executionContext)
{
const string Prefix = "http://www.";
Check.Argument.IsNotNull(executionContext, "executionContext");
HttpContextBase httpContext = executionContext.HttpContext;
string url = httpContext.Request.Url.ToString();
bool startsWith3W = url.StartsWith(Prefix, StringComparison.OrdinalIgnoreCase);
bool shouldContinue = true;
if (startsWith3W)
{
string newUrl = "http://" + url.Substring(Prefix.Length);
HttpResponseBase response = httpContext.Response;
response.StatusCode = (int) HttpStatusCode.MovedPermanently;
response.Status = "301 Moved Permanently";
response.RedirectLocation = newUrl;
response.SuppressContent = true;
response.End();
shouldContinue = false;
}
return shouldContinue ? TaskContinuation.Continue : TaskContinuation.Break;
}
}
You would just need to check for the url ending with a / in your code.
** Note this does use a 3rd party dll - System.Web.MVC.Extensibility namespace. **
It dosnt matter really for Google, but what does matter is if both urls'
http://domain.com/products and http://domain.com/products/ show the same page, you also need to watch with windows servers that links to your site like from external pages where the user has typed http://domain.com/PRODUCTS/ will aloso be seen as a diffrent page as the web is case sensitive.
There is away round this with the use of canonical url meta tag, it tell s google what the page name is really, so will avoid duplicate pages which ant really diuplicate
http://googlewebmastercentral.blogspot.com/2009/02/specify-your-canonical.html
you need to check the URI in the INIT event and check the URI to see if it coming in with the slash, if it is, simply do a redirect and add the 301 header to the output response.

Find application root URL without using ~

I need to construct the URL of a page in a String, to send it an email (as part of an email verification system). If i use the ~ symbol to denote the app root, it is taken literally.
The app will be deployed on a server on three different sites (on different ports) and each site can be accessed via 2 different URLs (one for LAn and one for internet).
So hardcoding the URL is out of question. I want to construct the url to verify.aspx in my application
Please help
You need this:
HttpContext.Current.Request.ApplicationPath
It's equivalent to "~" in a URL.
http://msdn.microsoft.com/en-us/library/system.web.httprequest.applicationpath.aspx
Unfortunately none of the methods listed generated the full url starting from http://---.
So i had to extract these from request.url. Something like this
Uri url=HttpContext.Current.Request.Url;
StringBuilder urlString = new StringBuilder();
urlString.Append(url.Scheme);
urlString.Append("://");
urlString.Append(url.Authority);
urlString.Append("/MyDesiredPath");
Can someone spot any potential problems with this?
Try:
HttpRequest req = HttpContext.Current.Request;
string url = req.Url.GetComponents(UriComponents.SchemeAndServer, UriFormat.SafeUnescaped)
+ ((req.ApplicationPath.Length > 1) ? req.ApplicationPath : "");
You need to put the URL as part of your web application's configuration. The web application does not know how it can be reached from the outside world.
E.g. consider a scenario where there's multiple proxies and load balancers in front of your web server... how would the web server know anything but its own IP?
So, you need to configure each instance of your web application by adding the base URL e.g. as an app setting in its web.config.
You can use HttpRequest.RawURL (docs here)property and base your URL on that, but if you are behind any kind of redirection, the RawURL may not reflect the actual URL of your application.
I ended up with this. I take the request url, and use the position of Request.ApplicationRoot to discover the left part of the uri. Should work with applications hosted in a virtual directory "/example" or in the root "/".
private string GetFullUrl(string relativeUrl)
{
if (string.IsNullOrWhiteSpace(relativeUrl))
throw new ArgumentNullException("relativeUrl");
if (!relativeUrl.StartsWith("/"))
throw new ArgumentException("url should start with /", "relativeUrl");
string current = Request.Url.ToString();
string applicationPath = Request.ApplicationPath;
int applicationPathIndex = current.IndexOf(applicationPath, 10, StringComparison.InvariantCultureIgnoreCase);
// should not be possible
if (applicationPathIndex == -1) throw new InvalidOperationException("Unable to derive root path");
string basePath = current.Substring(0, applicationPathIndex);
string fullRoot = string.Concat(
basePath,
(applicationPath == "/") ? string.Empty : applicationPath,
relativeUrl);
return fullRoot;
}
This has always worked for me:
string root = Request.Url.AbsoluteUri.Replace(Request.Url.PathAndQuery, "");

Resources