Tuesday, 25 September 2012

ASP.NET Web Forms Application Paths Related

This article is going to list all ASP.NET Web Forms application paths related properties and their values on the Request object. Below the test result are based on this scenario: local hosted IIS site named VirtualSite, first we access to http://localhost/VirtualSite/Redirect/dummy.aspx and there is a HttpModule to redirect the request to http://localhost/VirtualSite/Redirect/Redirect.aspx. The request has parameters "a=1&b=2&c=3". So here it is:

Request Property Value
ApplicationPath /VirtualSite
AppRelativeCurrentExecutionFilePath ~/Redirect/Redirect.aspx
CurrentExecutionFilePath /VirtualSite/Redirect/Redirect.aspx
FilePath /VirtualSite/Redirect/Redirect.aspx
Path /VirtualSite/Redirect/Redirect.aspx
QueryString {a=1&b=2&c=3}
RawUrl /VirtualSite/Redirect/Dummy.aspx?a=1&b=2&c=3
Url.AbsolutePath /VirtualSite/Redirect/Redirect.aspx
Url.AbsoluteUrl http://localhost:25739/VitualSite/Redirect/Redirect.aspx?a=1&b=2&c=3
Url.Authority localhost:25739
Url.DnsSafeHost localhost
Url.Host localhost
Url.LocalPath /VitualSite/Redirect/Redirect.aspx
Url.OriginalString http://localhost:25739/VitualSite/Redirect/Redirect.aspx?a=1&b=2&c=3
Url.PathAndQuery /VitualSite/Redirect/Redirect.aspx?a=1&b=2&c=3
Url.Port 25739
Url.Query ?a=1&b=2&c=3
Url.Scheme http

Since there is a redirect, as you can see, only the RawUrl contains the very original request, all other values are for the redirected Url, event the Request.Url.OriginalString

Thursday, 6 September 2012

Do not mix using HtmlTextWriter and WebControl itself to set its attributes

Have a look the simplified code below first. The code is inside a ButtonControl class (assuming there is no null reference exception for CssClass property).


What does it do? First in the Render method we set the class to "Disabled" if Enabled property is false. Later when AddAttributesToRender method fired during base.Render() it will attach more CSS classes on the web control. All look good, right? No. It won’t work when Enabled == false.

Why? Check what the base.AddAttributesToRender() in line 16 does first. The AddAttributesToRender method will copy every single attribute from the web control into the HtmlTextWriter for page rendering later. If the attribute name has already existed in the HtmlTextWriter then the value of this attribute is abandoned to avoid value overwritten. This rule doesn't apply for Style attribute. For Style attribute, the value will be appended at the end of existing style string.

Ok, in our case when Enabled == false, since we have already set the Class attribute equal to "Disabled" then no matter how many other CssClass values assign to the web control directly those values will be abandoned when base. AddAttributesToRender() called.

So here is my simple advice: see the title of this article. Since we can always set attributes value on web control level it is unnecessary to touch the HtmlTextWriter under any condition.