URL mappings and incorrect form action URL
You can use URL mappings in your web.config to create better URLs SEO-wise, or as in my case, to create a duplicate version of a page without actually duplicating code. I created an urlMappings section and a couple of mappings in my web.config and it seemed to work great.
<urlMappings enabled="true"> <!-- This is needed since the sitemap does not allow duplicate urls --> <add url="~/NewDir/Default.aspx" mappedUrl="~/OldDir/Default.aspx" /> <add url="~/NewDir/Equipment.aspx" mappedUrl="~/NewDir/Equipment.aspx" /> </urlMappings>
However the HTML form action on each of the new mapped pages pointed to the old page, ie “/OldDir/Default.aspx”. I don’t know why ASP.NET insists on using the old URL rather than the real requested URL, but I guess it could be due to some security issue in some rare situation. There’s of course a number of different ways to correct this form action URL. One way is to simply set an action URL in you page load handler:
Form.Action = Request.RawUrl;
Request.RawUrl contains the actual requested URL. This means you have to do this on every mapped page. It just doesnt feel right.
Another approach I read about on blog post by Scott Gu is to use ControlAdapters. A ControlAdapter can be used to alter the rendering of a WebControl. In this case I want to alter a HtmlForm control and its Action property. The use of a ControlAdapter is registered in a browser definition file.
<controlAdapters> <adapter controlType="System.Web.UI.HtmlControls.HtmlForm" adapterType="Kraftvaerk.MappedUrlHtmlFormControlAdapter" /> </controlAdapters>
You implement a ControlAdapter by inheriting from System.Web.UI.Adapters.ControlAdapter.
public class MappedUrlHtmlFormControlAdapter : System.Web.UI.Adapters.ControlAdapter
{
protected override void Render(System.Web.UI.HtmlTextWriter writer)
{
// Override the Action property
((System.Web.UI.HtmlControls.HtmlForm)Control).Action = Page.Request.RawUrl;
base.Render(writer);
}
}
By using a ControlAdapter you don’t have to change a single line in your code-behind files, so if you have a lot of mapped URLs this approach is much easier to maintain. However, keep in mind that the adapter will be used on all pages, and therefore could break some logic that expects the default form action url in ASP.NET.
Af:
Andreas Gehrke
Kategorier: Teknologi
