I use rewrite URLs on my site to get URLs like:
http://mysite.com/users/john
instead of
http://mysite.com/index.aspx?user=john
To achieve this without redistribution using IIS6 and access to the hosting server, I use the “404 approach”. When a request that the server cannot find, a 404-page map is displayed, since it is an aspx page that can be rewritten (I can configure the 404-display using the control panel on the hosting).
This is the code in Global.asax:
protected void Application_BeginRequest(object sender, EventArgs e)
{
string url = HttpContext.Current.Request.Url.AbsolutePath;
if (url.Contains("404.aspx"))
{
string[] urlInfo404 = Request.Url.Query.ToString().Split(';');
if (urlInfo404.Length > 1)
{
string requestURL = urlInfo404[1];
if (requestURL.Contains("/users/"))
{
HttpContext.Current.RewritePath("~/index.aspx?user=" + GetPageID(requestURL));
StoreRequestURL(requestURL);
}
else if (requestURL.Contains("/picture/"))
{
HttpContext.Current.RewritePath("~/showPicture.aspx?pictureID=" + GetPageID(requestURL));
StoreRequestURL(requestURL);
}
}
}
}
private void StoreRequestURL(string url)
{
url = url.Replace("http://", "");
url = url.Substring(url.IndexOf("/"));
HttpContext.Current.Items["VirtualUrl"] = url;
}
private string GetPageID(string requestURL)
{
int idx = requestURL.LastIndexOf("/");
string id = requestURL.Substring(idx + 1);
id = id.Replace(".aspx", "");
return id;
}
And in Page_Load on my main page, I set the correct URL in the action attribute in the form tag.
protected void Page_Load(object sender, EventArgs e)
{
string virtualURL = (string)HttpContext.Current.Items["VirtualUrl"];
if (!String.IsNullOrEmpty(virtualURL))
{
form1.Action = virtualURL;
}
}
, , postback , - ?
, , 404, , ( ), postback. :
http://mysite.com/users/john.aspx
- , (IIS6, /ISAPI- ).