Click here to Skip to main content
15,867,330 members
Articles / Web Development / ASP.NET

ASP.NET 4.5 Features - Part 1

Rate me:
Please Sign up or sign in to vote.
4.93/5 (46 votes)
21 Oct 2013CPOL10 min read 129.3K   89   31
In this article, you should have basic knowledge of web development and some features introduced in prior versions of .NET Framework, especially ASP.NET features.

.NET Framework 4.5 came up with lots of great features. Writing about all of them will not be possible but I would like to throw light on some features especially with regards to ASP.NET.

Now I am just wondering from where I should start and how I should start?

I think I should start talking about target audience.

Let me be clear that this article is not intended for those who want to learn ASP.NET Web Forms or ASP.NET MVC. In order to understand this article, you should have basic knowledge of web development and some features introduced in prior versions of .NET Framework, especially ASP.NET features.

Image 1

What Will We Learn Then?

We will not cover each and every ASP.NET feature introduced with 4.5. Rather, we will talk about some features which I personally felt were good and thought I should share. If you think that there is something else which has to be covered, you have the comments section and I will try to get it to you.

Agenda

  • Understand Asynchronous HTTP Modules and Handlers
  • WebSocket protocol support in ASP.NET 4.5
  • New Request Validation features
  • What’s next and conclusion?

Enough talking, let’s get back to work.

Understand Asynchronous HTTP Modules and Handlers.

HTTP modules and HTTP handlers are two words we commonly hear from every ASP.NET developer. Many times, we want to implement pre-processing logic before any web resource like image, text or aspx is requested. For example – We want to add a security check before actual page/resource processing starts.

HTTP modules emit lots of events in the ASP.NET request pipeline where we can write our own logic so it is termed as event based methodology. Each and every request passes through HTTP modules.

Image 2

HTTP handlers on the other hand won’t get executed for every request, it depends on the extension of resource we are requesting so it is termed as extension based methodology. Let’s say end user makes a request to image with .jpg extension but we internally retrieve the image from database and send it as a response. HTTP handler fits here best.

Image 3

If you are more curious about these two concepts and want to learn in-depth, click here.

Request Processing is ASP.NET

Now IIS web server maintains a pool of threads and whenever a new requests comes in, it just takes one thread from that pool and allocates it for request processing. As long as threads are available in the thread pool, ASP.NET will be able to serve all requests. But once all threads got busy processing the request and no free threads remain in thread pool, new request has to wait for thread to become free. Obviously, there is a waiting time and after that, the server will throw “HTTP 503 server busy” or “Server Unavailable” error.

Increasing the thread pool size doesn't really solve the problem.

Lack of threads is not the real problem, the real problem is existing threads are not getting used efficiently.

Image 4

Many times, our request processing thread will be waiting for our I/O to complete instead of executing code, which I call as inefficient use of thread. We should release the thread as soon as I/O operation starts and obtain a new thread as soon as it completes.

Synchronous HTTP Modules

Let’s talk about a scenario where we want to write a complex long running task in HTTP module.

Task may include:

  • reading from or writing to some text/xml file
  • may be some database operation
  • may be downloading something from web
Image 5

For demo purposes, let’s say we want to log details of all requests into database.

Now if we execute modules in a synchronous manner, it will degrade site performance a lot because it will keep request processing thread (which was allocated in the beginning) busy throughout database processing.

Asynchronous HTTP Modules

Now ASP.NET has a support for creating asynchronous HTTP modules. In this case, we will release the thread as soon as I/O or any other operation starts which won’t require CPU.

In order to do that, we will use asynchronous methods in HTTP modules instead of synchronous methods. In the example, we are using AddOnPostAuthorizeRequestAsync method which is the asynchronous version of synchronous event PostAcquireRequestState.

Image 6

Then What is New in ASP.NET 4.5?

Although previous versions of ASP.NET allowed the creation of asynchronous HTTP modules, with the introduction of Task in 4.0 and async/await keywords in 4.5, it has become much simpler.

In ASP.NET 4.5, we have a class called EventHandlerTaskAsyncHelper and a delegate type called TaskEventHandler using which we can integrate Task-based asynchronous methods with the older asynchronous programming model exposed by the ASP.NET HTTP Pipeline. Let’s have a quick look at the refactored version of the above code snippet.

Image 7

Synchronous HTTP Handlers

Let’s discuss about the image processing scenario we discussed above (while explaining HTTP handlers). Now if we create a synchronous HTTP handler for the same, it will just block the request processing thread for a long time. We should release the thread to thread pool as soon as we start retrieving image from database (so that it can serve some other request) and should allocate a new thread when retrieving completes.

Asynchronous HTTP Handlers

The ultimate solution will be Asynchronous HTTP handlers.

Normally, in order to create HTTP handler, we use IHttpHandler but in order to create Asynchronous HTTP handler, we will use IHttpAsyncHandler.

JavaScript
public class MyAsyncHandelerOldWay: IHttpAsyncHandler
{
    public MyAsyncHandelerOldWay()
    {
    }
    public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallbackcb, object
extraData)
    {
        //......
    }
    public void EndProcessRequest(IAsyncResult result)
    {
        //......
    }
    public bool IsReusable
    {
        //......
    }
    public void ProcessRequest(HttpContext context)
    {
        //......
    }
}

Then What is New in ASP.NET 4.5?

Same problem. It’s too complex to implement. But .NET 4.5 made it easy to implement with async/await keyword and a class called HttptaskAsyncHandler.

JavaScript
publicclassMyAsyncHandeler:HttpTaskAsyncHandler
{
    public MyAsyncHandeler()
    {
    }
    public override async Task ProcessRequestAsync(HttpContext context)
    {
        SqlCommand cmd = newSqlCommand();
        Object Image= await cmd.ExecuteScalarAsync();
        context.Response.BinaryWrite((byte[])Image);
        context.Response.End();
    }
}

WebSocket Support in ASP.NET 4.5

HTML 5 WebSocket is a known feature to everyone by now. It brings sockets to the web.

Clients connect to a server and sends an HTTP request (prefixed by “ws://” or “wss://”) with special headers, then web server response back HTTP 101 with special response headers. This is how handshaking works in case of WebSockets. This will establish a secure, real time communication between client and server over HTTP.

Image 8

Now it’s not required to use techniques like long pooling or periodic pooling to simulate the socket behavior in web, now it’s possible without much effort because of WebSockets.

What’s New in ASP.NET 4.5?

Now in order to work with WebSockets, we need:

  1. Client side JavaScript APIs which we can use:
    • for initiating connection
    • for sending messages to server
    • for receiving messages from server
  2. Server side .NET APIs for creating and hosting WebSocket server

Client Side APIs

Now for client side scripting, we have APIs provided by HTML 5.

Code 1 – Initiating Connection

JavaScript
window.onload = function ()
{
    //Url of WebSocket Server
    var url = "ws://localhost:9495/ChatServer.ashx?Name=Sukesh";
    var ws = new WebSocket (url);
}

Code 2- Sending Messages

JavaScript
$('#BtnSend').click
(
    function ()
    {
        ws.send($('#TxtMessage').val());
        $('#TxtMessage').val('');
    }
);

Code 3 – Receiving Messages

JavaScript
ws.onmessage = function (e)
{
    $('#ResponseDiv').append("<br>" + e.data.toString());
}

Note: $ in above code is from jQuery. For Dom manipulation, we are using jQuery.

Server Side APIs

ASP.NET 4.5 provides APIs using which developers can easily (word easy is very important here) write code which will:

  • Accept client’s WebSocket request and upgrades HTTP Get request to WebSocket request.
    Code for accepting WebSocket request:
    JavaScript
    HttpContext.Current.AcceptWebSocketRequest (// WebSocket delegate goes here)

    Note: In case of web forms, this code will be written in either HTTP Module or in HTTP Handler and in case of MVC, we will use Web APIs.

    Code for WebSocket delegate:
    JavaScript
    private async Task MyProcessTask(AspNetWebSocketContext context)
    {
        //Code goes here
    }
  • Read string or binary data from WebSocket object synchronously or asynchronously. Code for creating WebSocket object:
    JavaScript
    WebSocket socket = context.WebSocket; //context -> parameter of MyProcessTask
    Code for receive message:
    JavaScript
    ArraySegment<byte> buffer = newArraySegment<byte>(newbyte[1024]);
    //receive data from Client
    WebSocketReceiveResult result = await socket.ReceiveAsync(
    buffer, CancellationToken.None);
    Code for send message:
    JavaScript
    //Send data to client
    await socket.SendAsync(
    buffer, WebSocketMessageType.Text, true, CancellationToken.None);

    Code example shows that WebSockets requests run completely asynchronously inside.

    Application was waiting for client message asynchronously and for that, we are using await socket.ReceiveAsync.

    Similarly, asynchronous messages are sent to a client by calling await socket.SendAsync.

New Request Validation Features in ASP.NET 4.5

Request validation is one of the important features in ASP.NET. It examines the incoming requests and determines whether it contains potential dangerous content.

  • What is meant by dangerous content?

    Any HTML or JavaScript code which is added for malicious purpose.
  • What is meant by request content here?

    It means posted values, query string, cookies and header of the request.
  • Why Request validation is required?

    It avoids XSS (Cross-site-scripting). Let’s say we have a textbox and button in page. When someone clicks the button, value in the textbox will be displayed in the page itself. Now let’s say if someone puts some kind of JavaScript code with script tag in textbox and when we try to write textbox content into the page, browser will execute the JavaScript code.
  • What happens if request validation fails?

    ASP.NET will throw an error “potentially dangerous value was detected" error and stops page processing.

It’s going to be a big problem if we want our application to accept HTML content. Example for application which will accept HTML content are Forum sites.

Solution – Disable Request Validation

  • Either at Page level as:
    JavaScript
    <%@PagevalidateRequest="false"%> 
  • Or at application level as:
    JavaScript
     <configuration>
    <system.web>
    <pagesvalidateRequest="false" />
    </system.web>
    </configuration> 

Is This good?

Obviously no!!! Because we have to validate each and every control in page so that XSS will not affect. Project requirement says only some controls are going to accept HTML content hence there is no sense in disabling request validation for all the controls in page (or application).

What ASP.NET 4.5 Has in its Pocket?

It provides 2 new features:

  1. Deferred request validation
  2. Introduction of ValidateRequestMode property

In order to understand these two features, let's create a simple form as follows:

Image 9

In order to solve this issue, we will navigate to web.config and will change requestValidationMode to 4.5 (new in ASP.NET 4.5).

XML
<system.web>
<compilationdebug="true"targetFramework="4.5"/>
<httpRuntimetargetFramework="4.5"requestValidationMode="4.5"/>
</system.web>  

It will just vanish the error. Now it’s time to consume the values in code behind for further processing. So let’s write some code in button click handler.

Image 10

It seems like the error is still there. The only difference now is that it is coming when we try to access the value. The call to Request.Form["forum_post"] still triggers request validation for that specific request value.

This is what we call deferred request validation.

But How to Access Those Values?

For that, we will use Request.Unvalidated.Form.

Example:

JavaScript
stringHtmlContent = Request.Unvalidated.Form["TxtHtmlContents"];

What If I Want to useServer Side Controls?

This question only applies for ASP.NET Web Forms. In the above example, we are using input textboxes (HTML controls). Now let’s try the same example with Server side textboxes.

HTML
<div>
    (Html Contents): <br/>Server Textbox 
<asp:TextBoxrunat="server"ID="TxtHtmlContents"/><br/>
    (Normal Contents): <br/>Server Textbox 
<asp:TextBoxrunat="server"ID="TxtNormalContents"/><br/>
<asp:ButtonID="Button1"Text="Submit"runat="server"OnClick="Button1_Click"name="Address"/>
</div> 

We will see a strange behavior when we execute the code. Put some HTML content in textbox and click on button. We will get the same “Potential Error”. Setting requestValidationModeto 4.5 just delegates request validation from one time to other time (time when we try to retrieve values). When we closely look into the ASP.NET life cycle events,we will find that just before the Page_Load event, an event called LoadPostBackData gets fired, which will get all the values from posted data and load them into corresponding textboxes. It means, behind the scenes, ASP.NET is trying to access the values from posted form data which is causing error.

What is the Solution?

Now the good news is that ASP.NET 4.5 added a new property to every server control called ValidateRequestMode. Set it to “disabled”. Using this property, we can disable request validation for individual controls.

Some Small Important Features Introduced in 4.5

There are some very small but useful features which I want to address.

  • Automatic Html encoding with <%: %>

  • Unobtrusive validation –

    which will significantly reduce the amount of JavaScript rendered inline in the page markup and thus reduces the overall page size.
  • New features with regards to HTML 5

    • TextMode property of Textbox supports more values now like email, datetime
    • Many HTML 5 controls support runat=”server” attribute in order to support “~” sign while specifying URL
    • File upload control supports multi file upload

What is Next and Conclusion?

In this article, we tried to understand 3 new features in ASP.NET 4.5 and I hope you enjoyed it. We started our journey with Asynchronous HTTP modules and Handlers, then we had demo on web sockets and ended up with new request validation features.

In the further coming series, we will talk about improvements made on ASP.NET MVC.

  • ASP.NET Web API
  • Asynchronous controllers
  • Display Mode support

Thanks for reading. Your feedbacks, comments and ratings not only motivate us, but also improve us.

Keep coding and keep sharing.

For more stuff like this, click here. Subscribe to article updates or follow at twitter @SukeshMarla

Click to get more on ASP.NET /.NET and C# learning stuffs

Do go through this article once which talks about 5 important .NET 4.5 new features.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Founder Just Compile
India India
Learning is fun but teaching is awesome.

Who I am? Trainer + consultant + Developer/Architect + Director of Just Compile

My Company - Just Compile

I can be seen in, @sukeshmarla or Facebook

Comments and Discussions

 
PraiseGood Post Pin
Member 1276622128-Sep-16 22:51
Member 1276622128-Sep-16 22:51 
PraiseReally nice post https://codeproject.global.ssl.fastly.net/script/Forums/Images/thumbs_up.gif Pin
Member 1276622128-Sep-16 22:54
Member 1276622128-Sep-16 22:54 
GeneralMy vote of 5 Pin
cotbot19-Jul-14 2:49
cotbot19-Jul-14 2:49 
GeneralRe: My vote of 5 Pin
Marla Sukesh20-Jul-14 4:36
professional Marla Sukesh20-Jul-14 4:36 
QuestionNice Article Pin
Rajesh B Prajapati3-Dec-13 2:53
Rajesh B Prajapati3-Dec-13 2:53 
AnswerRe: Nice Article Pin
Marla Sukesh20-Jul-14 4:36
professional Marla Sukesh20-Jul-14 4:36 
QuestionNext part Pin
kiquenet.com7-Nov-13 21:40
professionalkiquenet.com7-Nov-13 21:40 
AnswerRe: Next part Pin
Marla Sukesh20-Jul-14 4:37
professional Marla Sukesh20-Jul-14 4:37 
GeneralMy vote of 5 Pin
Renju Vinod16-Sep-13 20:35
professionalRenju Vinod16-Sep-13 20:35 
GeneralRe: My vote of 5 Pin
Marla Sukesh17-Sep-13 17:13
professional Marla Sukesh17-Sep-13 17:13 
GeneralMy vote of 5 Pin
Monjurul Habib15-Aug-13 8:08
professionalMonjurul Habib15-Aug-13 8:08 
GeneralRe: My vote of 5 Pin
Marla Sukesh15-Aug-13 8:22
professional Marla Sukesh15-Aug-13 8:22 
GeneralMy vote of 5 Pin
manoj.jsm11-Aug-13 23:32
manoj.jsm11-Aug-13 23:32 
GeneralRe: My vote of 5 Pin
Marla Sukesh12-Aug-13 9:31
professional Marla Sukesh12-Aug-13 9:31 
GeneralMy vote of 5 Pin
Adarsh chauhan5-Aug-13 23:25
professionalAdarsh chauhan5-Aug-13 23:25 
GeneralRe: My vote of 5 Pin
Marla Sukesh5-Aug-13 23:29
professional Marla Sukesh5-Aug-13 23:29 
GeneralMy vote of 5 Pin
Shivprasad koirala5-Aug-13 16:56
Shivprasad koirala5-Aug-13 16:56 
GeneralRe: My vote of 5 Pin
Marla Sukesh5-Aug-13 17:04
professional Marla Sukesh5-Aug-13 17:04 
GeneralMy vote of 5 Pin
adriancs5-Aug-13 15:49
mvaadriancs5-Aug-13 15:49 
GeneralRe: My vote of 5 Pin
Marla Sukesh5-Aug-13 15:50
professional Marla Sukesh5-Aug-13 15:50 
GeneralMy vote of 5 Pin
Jean Paul V.A5-Aug-13 10:34
Jean Paul V.A5-Aug-13 10:34 
GeneralRe: My vote of 5 Pin
Marla Sukesh5-Aug-13 15:47
professional Marla Sukesh5-Aug-13 15:47 
QuestionInteresting, but pointless Pin
Vitaly Tomilov5-Aug-13 10:09
Vitaly Tomilov5-Aug-13 10:09 
AnswerRe: Interesting, but pointless Pin
HaBiX5-Aug-13 10:26
HaBiX5-Aug-13 10:26 
GeneralRe: Interesting, but pointless Pin
Vitaly Tomilov5-Aug-13 10:31
Vitaly Tomilov5-Aug-13 10:31 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.