Friday, May 28, 2010

Extensible Request Validation

ASP.NET request validation searches incoming HTTP request data for strings that are commonly used in cross-site scripting (XSS) attacks. If potential XSS strings are found, request validation flags the suspect string and returns an error. The built-in request validation returns an error only when it finds the most common strings used in XSS attacks. Previous attempts to make the XSS validation more aggressive resulted in too many false positives. However, customers might want request validation that is more aggressive, or conversely might want to intentionally relax XSS checks for specific pages or for specific types of requests.

In ASP.NET 4, the request validation feature has been made extensible so that you can use custom request-validation logic. To extend request validation, you create a class that derives from the new System.Web.Util.RequestValidator type, and you configure the application (in the httpRuntime section of the Web.config file) to use the custom type. The following example shows how to configure a custom request-validation class:

<httpRuntime requestValidationType="Samples.MyValidator, Samples" />



The new requestValidationType attribute requires a standard .NET Framework type identifier string that specifies the class that provides custom request validation. For each request, ASP.NET invokes the custom type to process each piece of incoming HTTP request data. The incoming URL, all the HTTP headers (both cookies and custom headers), and the entity body are all available for inspection by a custom request validation class like that shown in the following example:



public class CustomRequestValidation : RequestValidator
{
protected override bool IsValidRequestString(
HttpContext context, string value,
RequestValidationSource requestValidationSource,
string collectionKey,
out int validationFailureIndex)
{...}
}

For cases where you do not want to inspect a piece of incoming HTTP data, the request-validation class can fall back to let the ASP.NET default request validation run by simply calling base.IsValidRequestString.

Expanding the Range of Allowable URLs

ASP.NET 4 introduces new options for expanding the size of application URLs. Previous versions of ASP.NET constrained URL path lengths to 260 characters, based on the NTFS file-path limit. In ASP.NET 4, you have the option to increase (or decrease) this limit as appropriate for your applications, using two new httpRuntime configuration attributes. The following example shows these new attributes.

<httpRuntime maxRequestPathLength="260" maxQueryStringLength="2048" />




To allow longer or shorter paths (the portion of the URL that does not include protocol, server name, and query string), modify the maxRequestPathLength attribute. To allow longer or shorter query strings, modify the value of the maxQueryStringLength attribute.



ASP.NET 4 also enables you to configure the characters that are used by the URL character check. When ASP.NET finds an invalid character in the path portion of a URL, it rejects the request and issues an HTTP 400 error. In previous versions of ASP.NET, the URL character checks were limited to a fixed set of characters. In ASP.NET 4, you can customize the set of valid characters using the new requestPathInvalidChars attribute of the httpRuntime configuration element, as shown in the following example:



 



<httpRuntime requestPathInvalidChars="&lt;,&gt;,*,%,&amp;,:,\,?"  />




By default, the requestPathInvalidChars attribute defines eight characters as invalid. (In the string that is assigned to requestPathInvalidChars by default, the less than (<), greater than (>), and ampersand (&) characters are encoded, because the Web.config file is an XML file.) You can customize the set of invalid characters as needed.

Permanently Redirecting a Page

It is common practice in Web applications to move pages and other content around over time, which can lead to an accumulation of stale links in search engines. In ASP.NET, developers have traditionally handled requests to old URLs by using by using the Response.Redirect method to forward a request to the new URL. However, the Redirect method issues an HTTP 302 Found (temporary redirect) response, which results in an extra HTTP round trip when users attempt to access the old URLs.

ASP.NET 4 adds a new RedirectPermanent helper method that makes it easy to issue HTTP 301 Moved Permanently responses, as in the following example:

RedirectPermanent("/newpath/foroldcontent.aspx");

ClientIDMode in ASP.NET 4.0

One of the more anticipated features of ASP.NET 4.0 – is the new ClientIDMode property, which can be used to force controls to generate clean Client IDs that don’t follow ASP.NET’s munged NamingContainer ID conventions. To be clear, NamingContainer IDs are necessary for complex controls and pages that nest many things inside of a single context, but for most application level Web design scenarios those munged IDs get in the way and don’t provide a lot of value.

The munged IDs affect all sorts of development scenarios from design and CSS styling where ID haven’t been predictable for #id styling:

#ctl00_content_txtName 
{
font-weight: bold;
}



vs the more expected:



#txtName
{
font-weight: bold;
}



And even more so there’s the whole nightmare of ClientIds in script pages where code like this:



<script type="text/javascript">
var txtName = $("<%= txtName.ClientID %>");
var txtTitle = $("[id$=_txtTitle]");
</script>



or some other pre-generation code is necessary to get client id’s properly referenced in script code.



ClientIDMode


In prior versions of ASP.NET you had to live with the problem or work around with various hacks. In ASP.NET 4.0 things get a little easier via the new ClientIDMode property which allows you to specify exactly how a ClientID is generated.



The idea is simple: you get a new ClientIDMode property on all ASP.NET controls which can be set either at the actual control or somewhere up the NamingContainer chain. If the ClientIDMode property is not set on a control it inherits the setting from the nearest NamingContainer with the exception of  the <asp:Content> placeholder which doesn’t participate in ClientIDMode processing (bummer!).



This means if you choose to you can set ClientIDMode on the Page level and it will trickle down into all the child controls on the page, but a custom naming container like a User Control can still override the ClientIDMode to enforce it’s naming container requirements. It’ll be interesting to see how much existing code might break based on this inheritance scheme as custom controls may lose controls over their ClientID naming if the ClientIDMode property isn’t set explicitly.



Anyway let’s take a look at a very simple example and how the ClientIDMode property affects the ID rendering. Imagine you have a page that uses a master page and is set up like this:



<%@PageTitle=""Language="C#"MasterPageFile="~/Site.Master"AutoEventWireup="true" 
CodeBehind="WebForm2.aspx.cs"
Inherits="WebApplication1.WebForm2"
ClientIDMode="Predictable"
%>

<asp:ContentID="content"ContentPlaceHolderID="content"runat="server"ClientIDMode="Static" >
<asp:TextBox runat="server"ID="txtName"ClientIDMode="Static" />
</asp:Content>



Here’s what the various values for the txtName property can look like:



AutoID



This is the existing behavior in ASP.NET 1.x-3.x where full naming container munging takes place.



<input name="ctl00$content$txtName" type="text" id="ctl00_content_txtName" />



In Beta 2 this is the default value for the Page. According to the latest VS 2010 documentation however, the default behavior by release time will be Predictable.



Static

This option forces the control’s ClientID to use its ID value directly. No naming container naming at all is applied and you end up with clean client ids:



<inputname="ctl00$content$txtName"type="text"id="txtName" />



This option is what most of us want to use, but you have to be clear on that this can potentially cause conflicts with other control on the page. If there are several instances of the same naming container (several instances of the same user control for example) there can easily be a client ID naming conflict. It’s basically up to you to decide whether this is a problem or not.



Note that if you assign Static to a Databound control like a list child controls in templates do not get unique IDs either, so for list controls where you rely on unique Id for child controls you’ll probably want to use Predictable rather than Static. More on this a little later when I discuss ClientIDRowSuffix.



Predictable



The previous two values are pretty self-explanatory. Predictable however, requires some explanation. To me at least it's not in the least bit predictable :-}.

MSDN defines this enum value as follows:




This algorithm is used for controls that are in data-bound controls. The ClientID value is generated by concatenating the ClientID value of the parent naming container with the ID value of the control. If the control is a data-bound control that generates multiple rows, the value of the data field specified in the ClientIDRowSuffix property is added at the end. For the GridView control, multiple data fields can be specified. If the ClientIDRowSuffix property is blank, a sequential number is added at the end instead of a data-field value. Each segment is separated by an underscore character (_).




The key that makes this value a bit confusing is that it relies on the parent NamingContainer’s ClientID to build it’s own client ID value. Which effectively means that the value is not predictable at all but rather very tightly coupled to the parent naming container’s ClientIDMode setting.



For our simple textbox example, if the ClientIDMode property of the parent naming container (Page in this case) is set to “Predictable” you’ll get this:



<input name="ctl00$content$txtName" type="text" id="content_txtName" />



which gives a name that walk up to the currently active naming container (the MasterPage content container) and starts the name from there downward. Think of this as a semi unique name that’s guaranteed unique only for the naming container.

If on the other hand the Page is set to “AutoID” you get with Predicable on txtName:



<input name="ctl00$content$txtName" type="text" id="ctl00_content_txtName" />



The latter is effectively the same as if you specified AutoID in this scenario because it inherits the AutoID naming from the Page and Content control of the page.  But again – predictable behavior always depends on the parent naming container and how it generates its id so the ID may not always be exactly the same as the AutoID generated value because somewhere in the NamingContainer chain the ClientIDMode setting may be set to a different value. For example if you had another naming container in the middle that was set to Static you’d end up effectively with an ID that starts with the NamingContainers' ID rather than the whole ctl000_content munging.



The most common use however for Predictable will be for DataBound controls, which results in a each data bound item to get a unique ClientID.



Predictable is useful, but only if all naming containers down the chain use this setting. Otherwise you’re right back to the munged Ids that are pretty unpredictable.



Inherit



The final setting is Inherit which is the default for all controls except Page (AFAIK). This means that controls by default inherit the naming container’s ClientIDMode setting.



Inheritance


The explicit values are pretty obvious in what they do and when they are applied to individual controls. AutoID is classic behavior, Static is what we want in typical client centric apps, and Predictable is what you typically will want to use for list controls and anything that has possible naming conflicts.



Things get a little more tricky with inheritance of these settings. Specicfically the ClientIDMode property inherits from a NamingContainer down. Unlike most other ASP.NET hierarchy inheritance the ClientIDMode inheritance is based on the NamingContainer not on the Parent Container.



What this means is that if you set ClientIDMode="Static" on a Page or MasterPage all controls inherit that settings:



<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true"          CodeBehind="WebForm2.aspx.cs" Inherits="WebApplication1.WebForm2"           ClientIDMode="Static" %>



If you don’t set the ClientIDMode on any other controls the entire page will use Static. Any UserControls can override the setting but all controls will use this setting.



Now imagine I do:



<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" 
CodeBehind="WebForm2.aspx.cs" Inherits="WebApplication1.WebForm2"
ClientIDMode="Predictable" %>



and I’m running inside of a master page and I put in a block of controls like this:



 <asp:Panel runat="server"  ClientIDMode="Static">
This is a test:
<asp:TextBox runat="server" ID="txtName" />
<asp:Button ID="btnSubmit" runat="server" Text="Go" />
</asp:Panel>



Quick what should you see? Unfortunately not what I would have expected – although it’s true to what the documentation advertises. The block above renders into:



<div>
This is a test:
<input name="ctl00$content$txtName" type="text" id="content_txtName" />
<input type="submit" name="ctl00$content$btnSubmit" value="Go" id="content_btnSubmit" />
</div>



What’s happening here is that even though we specified Static naming on the Panel (which is not a NamingContainer) Predictable naming is used which runs up to the nearest naming container – in this case the Master Page Content control and using that as its base for the name. If I want those controls to render with clean ids I need to explicitly mark the controls to use Static:



<asp:Panel runat="server"  ClientIDMode="Static">
This is a test:
<asp:TextBox runat="server" ID="txtName" ClientIDMode="Static" />
<asp:Button ID="btnSubmit" runat="server" Text="Go" ClientIDMode="Static" />
</asp:Panel>



or by changing the Page’s ClientIDMode to Static:



<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" 
CodeBehind="WebForm2.aspx.cs" Inherits="WebApplication1.WebForm2" ClientIDMode="Static" %>



With either of those in place I now get:



<div id="Panel1">
This is a test:
<input name="ctl00$content$txtName" type="text" id="txtName" />
<input type="submit" name="ctl00$content$btnSubmit" value="Go" id="btnSubmit" />
</div>



Notice that when page level ClientIDMode="Static" the <div> tag now renders with an explicit ID which is rather inconsistent (it’s not there if I just have ClientIDMode=”Static” on the Panel alone).



Note that you unfortunately cannot use an <asp:Content> control and specify the ClientIDMode like this:



<asp:Content ID="content" ContentPlaceHolderID="content" runat="server" ClientIDMode="Static">



This has no effect  on the controls contained inside of the Content container which still inherit the ClientIDMode from Page in this case. This is really annoying because the Content container certainly is part of the naming container hierarchy that is reflected in the ClientIDName for Predictable and AutoId.



There’s a way around this by using:




  • Static on the List Control


  • Predictable on all of the Child controls



This looks like this:



<asp:GridView runat="server" ID="gvProducts" AutoGenerateColumns="false"
ClientIDMode="Static" ClientIDRowSuffix="id"
DataSourceID="xmlDataSource"
>
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label runat="server" id="txtTitle" Text='<%# Eval("title") %>' ClientIDMode="Predictable"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label runat="server" id="txtId" Text='<%# Eval("id") %>' ClientIDMode="Predictable" />
</ItemTemplate>
</asp:TemplateField>

</Columns>
</asp:GridView>



which results in:



<table cellspacing="0" rules="all" border="1" id="Table2" style="border-collapse:collapse;">
<tr>
<th scope="col">&nbsp;</th><th scope="col">&nbsp;</th>
</tr><tr>
<td>
<span id="txtTitle_32">West Wind West Wind Web Toolkit</span>
</td><td>
<span id="txtId_32">32</span>
</td>
</tr></table>



This does produce what I would consider a desirable result although I had hoped that using Static on the list control without any further formatting would have produced this result. Unfortunately the Predictable setting on each of the child controls is required to get the clean ids into the child controls.





ClientIDRowSuffix


Another feature of the ClientID improvements in ASP.NET 4.0 is the ClientIDRowSuffix which can be applied to DataBound/List controls. I used it above in the grid to have the enumerated client id of the child controls use the value of an Id field from the database as the enumeration value. This setting basically determines how ID values for template controls in databound controls are generated, but it requires that the ClientIDMode is set to Predictable. It produces:



id="txtTitle_32"



where the _32 in this case comes from the Id of the data source which is nice than only using sequentially numbered values in previous versions of ASP.NET which were often worthless in client situations. Using an actual data value that can be looked retrieved on the client and sent back on an Ajax callback makes these IDs much more useful.



Wouldn’t it be nice if Client Row Ids could be generated?



What would be even nicer is that the generated ‘rows’ of a data bound control could optionally generate ids. In most Ajax situations the row level ID is really what’s useful – selections of rows for deletion, editing and updating always require an ID even if there are no child controls, but ASP.NET doesn’t provide an easy mechanism for embedding row ids. It sure would be get output like this:



 <tr id="content_gvProducts_33">
...
</tr>



This can be done with code in a GridView (and other list controls) with ItemCreated events it’s quite a pain to do this. For example for the gridview I’m using with a simple XmlDataSource control I have to do this:



protected void gvProducts_RowCreated(object sender, GridViewRowEventArgs e)
{
object dataItem = e.Row.DataItem;

if (dataItem != null)
{
XPathNavigator nav = ((IXPathNavigable)dataItem).CreateNavigator();
if (nav != null)
e.Row.Attributes.Add("id", this.gvProducts.ID + "_" + nav.GetAttribute("id",""));
}
}



to produce output like this:



<tr id="gvProducts_33"> ... </tr> 



which is anything but intuitive for such a common scenario (although this IS a bit easier to grab the data if you use Entity list or DataTable binding).



Data List Controls and Static Produces Invalid HTML



One more note: Using Static on list controls with child controls and NOT using Predictable for child controls is problematic as it will generate static IDs for ALL template items:



<table cellspacing="0" rules="all" border="1" id="Table1" style="border-collapse:collapse;">
<tr>
<th scope="col">&nbsp;</th><th scope="col">&nbsp;</th>
</tr><tr>
<td>
<span id="txtTitle">West Wind West Wind Web Toolkit</span>
</td><td>
<span id="txtId">32</span>
</td>
</tr><tr>
<td>
<span id="txtTitle">West Wind West Wind Web Store</span>
</td><td>
<span id="txtId">33</span>
</td>
</tr>
</table>



This is invalid HTML since there are multiple controls with the same id attribute on the page which is clearly undesirable. To fix this remember to use Predictable on any of the child controls.



Or better yet stay away from server controls altogether in template columns – stick to plain HTML controls and use AJAX to update values to the server more interactively. :-}



How should we use ClientIDMode?


I suspect it’s going to take some time to figure out all the little nuances of the new ClientIDMode features. At the very least the Static option on individual controls allows you to explicitly force controls to use the name you want it to and that’s a win any way you look at it.



For now I think the following is what I want to use in typical page scenarios in my applications:




  • Add ClientIDMode="Static" to each Page  (or in web.config’s <pages> setting)


  • Add ClientIDMode="Predictable" explicitly to each List Control Children in Databound Template


  • Override explicitly to Predictable where naming conflicts are a problem and to AutoId for the extreme edge case


  • For Control Development leave at default behavior if possible (ie. Inherit from parent)


  • Override only when necessary and preferrably on individual subcontrols



Also for now I think it’s a good idea to EXPLICITLY specify a ClientIDMode on each page (or in your project) or explicitly declare the value in your web.config file:



<pages clientIDMode="Static" />



to ensure you get a predictable setting since the current Beta 2 implementation and the documentation are at odds of what the default value actually is.

ViewStateMode in ASP.Net 4.0

 

When asp.net introduced the concept of viewstate, it changed the way how developers maintain the state for the controls in a web page. Until then to keep the track of the control(in classic asp), it was the developer responsibility to manually assign the posted content before rendering the control again. Viewstate made allowed the developer to do it with ease. The developers are not bothered about how controls keep there state on post back.

Viewstate is rendered to the browser as a hidden variable __viewstate. Since viewstate stores the values of all controls, as the number of controls in the page increases, the content of viewstate grows large. It causes some websites to load slowly.

As developers we need viewstate, but actually we do not want this for all the controls in the page. Till asp.net 3.5, if viewstate is disabled from web.config (using <pages viewstate=”false”/> ..</pages>), then you can not enable it from the control level/page level. Both <%@ Page EnableViewState=”true”…. and <asp:textbox EnableViewState=”true” will not work in this case.

Lot of developers demands for more control over viewstate. It will be useful if the developers are able to disable it for the entire page and enable it for only those controls that needed viewstate. With ASP.NET 4.0, this is possible, a happy news for the developers. This is achieved by introducing a new property called ViewStateMode.

Let us see, What is ViewStateMode – Is a new property in asp.net 4.0, that allows developers to enable viewstate for individual control even if the parent has disabled it. This ViewStateMode property can contain either of three values

  1. Enabled- Enable view state for the control even if the parent control has view state disabled.
  2. Disabled - Disable view state for this control even if the parent control has view state enabled
  3. Inherit - Inherit the value of ViewStateMode from the parent, this is the default value.

To disable view state for a page and to enable it for a specific control on the page, you can set the EnableViewState property of the page to true, then set the ViewStateMode property of the page to Disabled, and then set the ViewStateMode property of the control to Enabled.

Find the example below.

Page directive - <%@ Page Language="C#"  EnableViewState="True" ViewStateMode="Disabled" .......... %>

Code for the control  - <asp:TextBox runat="server" ViewStateMode="Enabled" ............../>

Now the viewstate will be disabled for the whole page, but enabled for the TextBox.

ViewStateMode gives developers more control over the viewstate.