What's New in ASP.NET 4.5 and Visual Studio 2012 This document describes new features and enhancements that are being introduced in ASP.NET 4.5. It also describes improvements being made for web development in Visual Studio (Visual Web Developer). ASP.NET Core Runtime and FrameworkAsynchronously Reading and Writing HTTP Requests and Responses Improvements to HttpRequest handlingAsynchronously flushing a responseSupport for awaitand Task-Based Asynchronous Modules and Handlers Asynchronous HTTP modulesAsynchronous HTTP handlersNew ASP.NET Request Validation Features Deferred ("lazy") request validation Support for unvalidated requestsAntiXSS LibrarySupport for WebSockets Protocol Bundling and MinificationPerformance Improvements for Web HostingKey Performance FactorsRequirements for New Performance Features Sharing Common AssembliesUsing multi-Core JIT compilation for faster startupTuning garbage collection to optimize for memoryPrefetching for web applicationsASP.NET Web FormsStrongly Typed Data ControlsModel BindingSelecting dataValue providersFiltering by values from a controlHTML Encoded Data-Binding Expressions Unobtrusive ValidationHTML5 UpdatesASP.NET MVC 4ASP.NET Web Pages 2Visual Studio 2012 Release CandidateProject Sharing Between Visual Studio 2010 and Visual Studio 2012 Release Candidate (Project Compatibility)Configuration Changes in ASP.NET 4.5 Website TemplatesNative Support in IIS 7 for ASP.NET RoutingHTML EditorSmart TasksWAI-ARIA supportNew HTML5 snippetsExtract to user controlIntelliSense for code nuggets in attributes
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
What's New in ASP.NET 4.5 and Visual Studio 2012This document describes new features and enhancements that are being introduced in ASP.NET 4.5. It also
describes improvements being made for web development in Visual Studio (Visual Web Developer).
ASP.NET Core Runtime and Framework Asynchronously Reading and Writing HTTP Requests and Responses
Improvements to HttpRequest handling
Asynchronously flushing a response
Support for await and Task -Based Asynchronous Modules and Handlers
Asynchronous HTTP modules
Asynchronous HTTP handlers
New ASP.NET Request Validation Features
Deferred ("lazy") request validation
Support for unvalidated requests
AntiXSS Library
Support for WebSockets Protocol
Bundling and Minification
Performance Improvements for Web Hosting
Key Performance Factors
Requirements for New Performance Features
Sharing Common Assemblies
Using multi-Core JIT compilation for faster startup
Tuning garbage collection to optimize for memory
Prefetching for web applications
ASP.NET Web Forms
Strongly Typed Data Controls
Model Binding
Selecting data
Value providers
Filtering by values from a control
HTML Encoded Data-Binding Expressions
Unobtrusive Validation
HTML5 Updates
ASP.NET MVC 4
ASP.NET Web Pages 2
Visual Studio 2012 Release Candidate
Project Sharing Between Visual Studio 2010 and Visual Studio 2012 Release Candidate (Project
Compatibility)
Configuration Changes in ASP.NET 4.5 Website Templates
Automatic renaming of matching tag when you rename an opening or closing tag
Event handler generation
Smart indent
Auto-reduce statement completion
JavaScript Editor
Code outlining
Brace matching
Go to Definition
ECMAScript5 support
DOM IntelliSense
VSDOC signature overloads
Implicit references
CSS Editor
Auto-reduce statement completion
Hierarchical indentation.
CSS hacks support
Vendor specific schemas (-moz-,-webkit)
Commenting and uncommenting support
Color picker
Snippets
Custom regions
Page Inspector
Publishing
Publish profiles
ASP.NET precompilation and merge
IIS Express
Disclaimer
ASP.NET Core Runtime and Framework
Asynchronously Reading and Writing HTTP Requests and
Responses
ASP.NET 4 introduced the ability to read an HTTP request entity as a stream using
theHttpRequest.GetBufferlessInputStream method. This method provided streaming access to the request
entity. However, it executed synchronously, which tied up a thread for the duration of a request.
ASP.NET 4.5 supports the ability to read streams asynchronously on an HTTP request entity, and the abilityto flush asynchronously. ASP.NET 4.5 also gives you the ability to double-buffer an HTTP request entity,
which provides easier integration with downstream HTTP handlers such as .aspx page handlers and
The Stream reference returned by ASP.NET 4.5 from HttpRequest.GetBufferlessInputStream supports both
synchronous and asynchronous read methods. The Stream object returned
from GetBufferlessInputStream now implements both the BeginRead and EndRead methods. The
asynchronous Stream methods let you asynchronously read the request entity in chunks, while ASP.NET
releases the current thread between each iteration of an asynchronous read loop.
ASP.NET 4.5 has also added a companion method for reading the request entity in a bufferedway:HttpRequest.GetBufferedInputStream. This new overload works like GetBufferlessInputStream,
supporting both synchronous and asynchronous reads. However, as it reads, GetBufferedInputStream also
copies the entity bytes into ASP.NET internal buffers so that downstream modules and handlers can still
access the request entity. For example, if some upstream code in the pipeline has already read the request
entity using GetBufferedInputStream, you can still use HttpRequest.Form or HttpRequest.Files. This lets you
perform asynchronous processing on a request (for example, streaming a large file upload to a database),
but still run .aspx pages and MVC ASP.NET controllers afterward.
Asynchronously flushing a response
Sending responses to an HTTP client can take considerable time when the client is far away or has a low-
bandwidth connection. Normally ASP.NET buffers the response bytes as they are created by an
application. ASP.NET then performs a single send operation of the accrued buffers at the very end of
request processing.
If the buffered response is large (for example, streaming a large file to a client), you must periodically
callHttpResponse.Flush to send buffered output to the client and keep memory usage under control.
However, becauseFlush is a synchronous call, iteratively calling Flush still consumes a thread for the
duration of potentially long-running requests.
ASP.NET 4.5 adds support for performing flushes asynchronously using
the BeginFlush and EndFlush methods of theHttpResponse class. Using these methods, you can create
asynchronous modules and asynchronous handlers that incrementally send data to a client without tying
up operating-system threads. In between BeginFlush and EndFlushcalls, ASP.NET releases the current
thread. This substantially reduces the total number of active threads that are needed in order to support
long-running HTTP downloads.
Support for await and Task -Based Asynchronous Modules
and HandlersThe .NET Framework 4 introduced an asynchronous programming concept referred to as a task . Tasks are
represented by the Task type and related types in the System.Threading.Tasks namespace. The .NET
Framework 4.5 builds on this with compiler enhancements that make working with Task objects simple. In
the .NET Framework 4.5, the compilers support two new keywords: await and async. The await keyword is
syntactical shorthand for indicating that a piece of code should asynchronously wait on some other piece
of code. The async keyword represents a hint that you can use to mark methods as task-basedasynchronous methods.
The combination of await , async, and the Task object makes it much easier for you to write asynchronous
code in .NET 4.5. ASP.NET 4.5 supports these simplifications with new APIs that let you write asynchronous
HTTP modules and asynchronous HTTP handlers using the new compiler enhancements.
Suppose that you want to perform asynchronous work within a method that returns a Task object. The
following code example defines an asynchronous method that makes an asynchronous call to download
the Microsoft home page. Notice the use of the async keyword in the method signature and the await call
to DownloadStringTaskAsync.
private async Task
ScrapeHtmlPage(object caller, EventArgs e) {
WebClient wc = new WebClient();
var result = await wc.DownloadStringTaskAsync ("http://www.microsoft.com" );
// Do something with the result
}
That's all you have to write — the .NET Framework will automatically handle unwinding the call stack while
waiting for the download to complete, as well as automatically restoring the call stack after the download
is done.
Now suppose that you want to use this asynchronous method in an asynchronous ASP.NET HTTP module.
ASP.NET 4.5 includes a helper method (EventHandlerTaskAsyncHelper ) and a new delegate type(TaskEventHandler ) that you can use to integrate task-based asynchronous methods with the older
asynchronous programming model exposed by the ASP.NET HTTP pipeline. This example shows how:
public void Init(HttpApplication
context)
{
// Wrap the Task-based method so that it can be used with
// the older async programming model.
EventHandlerTaskAsyncHelper helper =
new EventHandlerTaskAsyncHelper (ScrapeHtmlPage);
// The helper object makes it easy to extract Begin/End methods out of
// a method that returns a Task object. The ASP.NET pipeline calls the
// Begin and End methods to start and complete calls on asynchronous
The new behavior makes it easier for different application components to look at different pieces of
request data without triggering request validation on other pieces.
Support for unvalidated requests
Deferred request validation alone doesn't solve the problem of selectively bypassing request validation.
The call to Request.Form["forum_post"] still triggers request validation for that specific request value.However, you might want to access this field without triggering validation because you want to allow
markup in that field.
To allow this, ASP.NET 4.5 now supports unvalidated access to request data. ASP.NET 4.5 includes a
newUnvalidated collection property in the HttpRequest class. This collection provides access to all of the
common values of request data, like Form, QueryString, Cookies, and Url.
Using the forum example, to be able to read unvalidated request data, you first need to configure the
application to use the new request validation mode:
<httpRuntime requestValidationMode="4.5" ...
/> You can then use the HttpRequest.Unvalidated property to read the unvalidated form value:
var s = context.Request.Unvalidated.Form["forum_post"];
Security Note: Use unvalidated request data with care! ASP.NET 4.5 added the unvalidated request
properties and collections to make it easier for you to access very specific unvalidated request data.
However, you must still perform custom validation on the raw request data to ensure that dangerous text
is not rendered to users.
AntiXSS Library
Due to the popularity of the Microsoft AntiXSS Library, ASP.NET 4.5 now incorporates core encoding
routines from version 4.0 of that library.
The encoding routines are implemented by the AntiXssEncoder type in the
new System.Web.Security.AntiXssnamespace. You can use the AntiXssEncoder type directly by calling any of
the static encoding methods that are implemented in the type. However, the easiest approach for using
the new anti-XSS routines is to configure an ASP.NET application to use the AntiXssEncoder class by
default. To do this, add the following attribute to the Web.config file:
it to a global BundleCollection instance. In the default templates, bundle configuration is performed in a
BundleConfig file. This default configuration creates bundles for all of the core scripts and css files used by
the templates.
Bundles are referenced from within views by using one of a couple possible helper methods. In order to
support rendering different markup for a bundle when in debug vs. release mode, the ScriptBundle andStyleBundle classes have the helper method, Render. When in debug mode, Render will generate markup
for each resource in the bundle. When in release mode, Render will generate a single markup element for
the entire bundle. Toggling between debug and release mode can be accomplished by modifying the
debug attribute of the compilation element in web.config as shown below:
Ideally, all websites should be active and in memory to assure quick response to the next request,
whenever it comes. Factors that can affect site responsiveness include:
The time it takes for a site to restart after an app pool recycles. This is the time it takes to launch a
web server process for the site when the site assemblies are no longer in memory. (The platform
assemblies are still in memory, since they are used by other sites.) This situation is referred to as"cold site, warm framework startup" or just "cold site startup."
How much memory the site occupies. Terms for this are "per-site memory consumption" or
"unshared working set."
The new performance improvements focus on both of these factors.
Requirements for New Performance Features
The requirements for the new features can be broken down into these categories:
Improvements that run on the .NET Framework 4.
Improvements that require the .NET Framework 4.5 but can run on any version of Windows.
Improvements that are available only with .NET Framework 4.5 running on Windows 8.
Performance increases with each level of improvement that you are able to enable.
Some of the .NET Framework 4.5 improvements take advantage of broader performance features that
apply to other scenarios as well.
Sharing Common Assemblies
Requirement: .NET Framework 4 and Visual Studio 11 Developer Preview SDK
Different sites on a server often use the same helper assemblies (for example, assemblies from a starter kitor sample application). Each site has its own copy of these assemblies in its Bin directory. Even though the
object code for the assemblies is identical, they're physically separate assemblies, so each assembly has to
be read separately during cold site startup and kept separately in memory.
The new interning functionality solves this inefficiency and reduces both RAM requirements and load
time. Interning lets Windows keep a single copy of each assembly in the file system, and individual
assemblies in the site Bin folders are replaced with symbolic links to the single copy. If an individual site
needs a distinct version of the assembly, the symbolic link is replaced by the new version of the assembly,
and only that site is affected.
Sharing assemblies using symbolic links requires a new tool named aspnet_intern.exe, which lets you
create and manage the store of interned assemblies. It is provided as a part of the Visual Studio 11
Developer Preview SDK. (However, it will work on a system that has only the .NET Framework 4 installed,
assuming you have installed the latest update.)
To make sure all eligible assemblies have been interned, you run aspnet_intern.exe periodically (for
example, once a week as a scheduled task). A typical use is as follows:
Once a site is running, its use of the garbage-collector (GC) heap can be a significant factor in its memory
consumption. Like any garbage collector, the .NET Framework GC makes tradeoffs between CPU time(frequency and significance of collections) and memory consumption (extra space that is used for new,
freed, or free-able objects). For previous releases, we have provided guidance on how to configure the GC
to achieve the right balance (for example, see ASP.NET 2.0/3.5 Shared Hosting Configuration).
For the .NET Framework 4.5, instead of multiple standalone settings, a workload-defined configuration
setting is available that enables all of the previously recommended GC settings as well as new tuning that
delivers additional performance for the per-site working set.
To enable GC memory tuning, add the following setting to the
Requirement: .NET Framework 4.5 running on Windows 8
For several releases, Windows has included a technology known as the prefetcher that reduces the disk-
read cost of application startup. Because cold startup is a problem predominantly for client applications,
this technology has not been included in Windows Server, which includes only components that areessential to a server. Prefetching is now available in the latest version of Windows Server, where it can
optimize the launch of individual websites.
For Windows Server, the prefetcher is not enabled by default. To enable and configure the prefetcher for
high-density web hosting, run the following set of commands at the command line:
At run time, these calls use reflection to read the value of the specified member and then display the
result in the markup. This approach makes it easy to data bind against arbitrary, unshaped data.
However, data-binding expressions like this don't support features like IntelliSense for member names,
navigation (like Go To Definition), or compile-time checking for these names.
To address this issue, ASP.NET 4.5 adds the ability to declare the data type of the data that a control is
bound to. You do this using the new ItemType property. When you set this property, two new typed
variables are available in the scope of data-binding expressions: Item and BindItem. Because the variables
are strongly typed, you get the full benefits of the Visual Studio development experience.For two-way data-binding expressions, use the BindItem variable:
This instructs model binding to try to bind a value from the query string to the keyword parameter at run
time. (This might involve performing type conversion, although it doesn't in this case.) If a value cannot be
provided and the type is non-nullable, an exception is thrown.
The sources of values for these methods are referred to as value providers, and the parameter attributes
that indicate which value provider to use are referred to as value provider attributes. Web Forms will
include value providers and corresponding attributes for all of the typical sources of user input in a WebForms application, such as the query string, cookies, form values, controls, view state, session state, and
profile properties. You can also write custom value providers.
By default, the parameter name is used as the key to find a value in the value provider collection. In the
example, the code will look for a query-string value named keyword (for example,
~/default.aspx?keyword=chef). You can specify a custom key by passing it as an argument to the
parameter attribute. For example, to use the value of the query-string variable named q, you could do
conversion was successful, and finally, using the value in the query. Model binding results in far less code
and in the ability to reuse the functionality throughout your application.
Filtering by values from a control
Suppose you want to extend the example to let the user choose a filter value from a drop-down list. Addthe following drop-down list to the markup and configure it to get its data from another method using
Typically you would also add an EmptyDataTemplate element to the GridView control so that the controlwill display a message if no matching products are found:
Globally by setting the static System.Web.UI.ValidationSettings.UnobtrusiveValidationMode propertytoUnobtrusiveValidationMode.WebForms (typically in the Application_Start method in the Global.asax
file). Individually for a page by setting the new UnobtrusiveValidationMode property of the Page classtoUnobtrusiveValidationMode.WebForms.
HTML5 Updates
Some improvements have been made to Web Forms server controls to take advantage of new features of
HTML5:
The TextMode property of the TextBox control has been updated to support the new HTML5 input
types likeemail, datetime, and so on.
The FileUpload control now supports multiple file uploads from browsers that support this HTML5feature.
Validator controls now support validating HTML5 input elements.
New HTML5 elements that have attributes that represent a URL now support runat="server". As a
result, you can use ASP.NET conventions in URL paths, like the ~ operator to represent the
application root (for example, <video runat="server" src="~/myVideo.wmv" />).
The UpdatePanel control has been fixed to support posting HTML5 input fields.
ASP.NET MVC 4
ASP.NET MVC 4 Beta is now included with Visual Studio 11 Beta. ASP.NET MVC is a framework for
developing highly testable and maintainable Web applications by leveraging the Model-View-Controller
(MVC) pattern. ASP.NET MVC 4 makes it easy to build applications for the mobile Web and includes
ASP.NET Web API, which helps you build HTTP services that can reach any device. For more information,
FileUpgradeFlags, UpgradeBackupLocation, and OldToolsVersion are used by the process that upgrades
the project file. They have no impact on working with the project in Visual Studio 2010.
VisualStudioVersion is a new property used by MSBuild 4.5 that indicates the version of Visual Studio for
the current project. Because this property didn’t exist in MSBuild 4.0 (the version of MSBuild that Visual
Studio 2010 SP1 uses), we inject a default value into the project file.
The VSToolsPath property is used to determine the correct .targets file to import from the path
represented by the MSBuildExtensionsPath32 setting.
There are also some changes related to Import elements. These changes are required in order to support
compatibility between both versions of Visual Studio.
Note: If a project is being shared between Visual Studio 2010 SP1 and Visual Studio 11 Beta on two
different computers, and if the project includes a local database in the App_Data folder, you must make
sure that the version of SQL Server used by the database is installed on both computers.
Configuration Changes in ASP.NET 4.5 WebsiteTemplates
The following changes have been made to the default Web.config file for site that are created using
website templates in Visual Studio 2012 Release Candidate:
In the <httpRuntime> element, the encoderType attribute is now set by default to use the AntiXSS
types that were added to ASP.NET. For details, see AntiXSS Library.
Also in the <httpRuntime> element, the requestValidationMode attribute is set to "4.5". This
means that by default, request validation is configured to use deferred ("lazy") validation. For details,
see New ASP.NET Request Validation Features.
The <modules> element of the <system.webServer> section does not containarunAllManagedModulesForAllRequestsattribute. (Its default value is false.) This means that if
you are using a version of IIS 7 that has not been updated to SP1, you might have issues with routing
in a new site. For more information, see Native Support in IIS 7 for ASP.NET Routing.
These changes do not affect existing applications. However, they might represent a difference in behavior
between existing websites and new websites that you create for ASP.NET 4.5 using the new templates.
Native Support in IIS 7 for ASP.NET Routing
This is not a change to ASP.NET as such, but a change in templates for new website projects that can
affect you if you are working a version of IIS 7 that has not had the SP1 update applied.
In ASP.NET, you can add the following configuration setting to applications in order to support routing:
When runAllManagedModulesForAllRequests is true, a URL like http://mysite/myapp/homegoes to
ASP.NET, even though there is no .aspx , .mvc, or similar extension on the URL.
An update that was made to IIS 7 makes the runAllManagedModulesForAllRequests settingunnecessary and supports ASP.NET routing natively. (For information about the update, see the Microsoft
Support article An update is available that enables certain IIS 7.0 or IIS 7.5 handlers to handle requests
whose URLs do not end with a period.)
If your website is running on IIS 7 and if IIS has been updated, you do not need to
setrunAllManagedModulesForAllRequests to true. In fact, setting it to true is not recommended,
because it adds unnecessary processing overhead to request. When this setting is true, all requests,
including those for .htm, .jpg, and other static files, also go through the ASP.NET request pipeline.
If you create a new ASP.NET 4.5 website using the templates that are provided in Visual Studio 2012 RC,
the configuration for the website does not include the runAllManagedModulesForAllRequests setting.
This means that by default the setting is false.
If you then run the website on Windows 7 without SP1 installed, IIS 7 will not include the required update.As a consequence, routing will not work and you will see errors. If you have a problem where routing does
not work, you can do either the following:
Update Windows 7 to SP1, which will add the update to IIS 7.
Install the update that's described in the Microsoft Support article listed previously.
Set runAllManagedModulesForAllRequests to true in that website's Web.config file. Note that this
will add some overhead to requests.
HTML Editor
Smart Tasks
In Design view, complex properties of server controls often have associated dialog boxes and wizards to
make it easy to set them. For example, you can use a special dialog box to add a data source to
a Repeater control or add columns to a GridView control.
However, this type of UI help for complex properties has not been available in Source view. Therefore,
Visual Studio 11 introduces Smart Tasks for Source view. Smart Tasks are context-aware shortcuts for
commonly used features in the C# and Visual Basic editors.
For ASP.NET Web Forms controls, Smart Tasks appear on server tags as a small glyph when the insertion
point is inside the element:
The Smart Task expands when you click the glyph or press CTRL+. (dot), just as in the code editors. It then
displays shortcuts that are similar to the Smart Tasks in Design view.
The JavaScript editor in Visual Studio 2012 Release Candidate is completely new and it greatly improves
the experience of working with JavaScript in Visual Studio.
Code outlining
Outlining regions are now automatically created for all functions, allowing you to collapse parts of the filethat aren’t pertinent to your current focus.
Brace matching
When you put the insertion point on an opening or closing brace, the editor highlights the matching one.
Go to Definition
The Go to Definition command lets you jump to the source for a function or variable.
ECMAScript5 supportThe editor supports the new syntax and APIs in ECMAScript5, the latest version of the standard that
describes the JavaScript language.
DOM IntelliSense
IntelliSense for DOM APIs has been improved, with support for many new HTML5 APIs
including querySelector , DOM Storage, cross-document messaging, and canvas. DOM IntelliSense is now
driven by a single simple JavaScript file, rather than by a native type library definition. This makes it easy
to extend or replace.
VSDOC signature overloadsDetailed IntelliSense comments can now be declared for separate overloads of JavaScript functions by
using the new <signature> element, as shown in this example:
function GetOrSet(key, value) {
/// <signature>
/// <summary>Gets the value</summary>
/// <param name="key" type="String">The key to get the value for</param>
/// <returns type="String" />
/// </signature>
/// <signature>
/// <summary>Sets the value</summary>
/// <param name="key" type="String">The key to set the value for</param>
/// <param name="value" type="String">The value to set</param>