Můžete potřebovat přesměrovat různé požadavky, ale já ukáži pro mne dvě zajímavé:
- přepsání url na jednu stránku, kde část url je předaná jako parametr
- přepsání části webu (máte alias)
Začneme přímo kódem
Kód bude umístěn v adresáři App_Code a může být samozřejmě předkompilován jako assembly.
using System.Web;
using System.IO;
using System.Web.UI;
public class RemapHandler : IHttpHandlerFactory
{
public IHttpHandler GetHandler(HttpContext Context, string requestType,
string url, string sPathTranslated)
{
IHttpHandler o;
// Handle weburl.cz, all pages are in subdirectory /weburldir on disk
if (Context.Request.Url.AbsoluteUri.ToLower().IndexOf("weburl.cz") > 0)
{
o = PageParser.GetCompiledPageInstance("/weburldir/" + Context.Request.Url.LocalPath,
Context.Server.MapPath("/weburldir/" + Context.Request.Url.LocalPath), Context);
return o;
}
string sPath = Context.Request.AppRelativeCurrentExecutionFilePath.ToLower();
string sScriptName = null;
// rewrite /articles/* to ArticlePage.aspx with ID
if (sPath.StartsWith("~/articles/"))
{
sScriptName = "~/ArticlePage.aspx";
}
else if (sPath.StartsWith("~/tag/"))
{
sScriptName = "~/TagPage.aspx";
}
else
{
if (Path.GetExtension(sPath) == ".aspx")
{
o = PageParser.GetCompiledPageInstance(Context.Request.Path, sPathTranslated, Context);
return o;
}
return new DefaultHttpHandler();
}
// pass data as ID
Context.Items["ID"] = System.IO.Path.GetFileNameWithoutExtension(sPathTranslated);
o = PageParser.GetCompiledPageInstance(sScriptName,
Context.Server.MapPath(sScriptName), Context);
return o;
}
public void ReleaseHandler(IHttpHandler handler)
{
}
}
Úprava web.config
Nyní je třeba říci ASP.NET, že má volat Váš handler a to provedeme přidáním informace do sekce <system.web>.
<system.web>
<httpHandlers>
<add verb="*" path="*.aspx" type="RemapHandler"/>
</httpHandlers>
….
Získání předaných parametrů
V případě přepisu url si předáváme data v ID a získáme je jednoduše např. v Page_Load:
protected void Page_Load(object sender, EventArgs e)
{
string sId = (string)Context.Items["ID"];
…
}
Tak a přepisovací minimum máme za sebou.