Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

ASP.NET 4.5 Features - Part 1

0.00/5 (No votes)
21 Oct 2013 4  
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.

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.

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.

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.

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

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.

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.

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.

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.

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.

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

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

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

Code 3 – Receiving Messages

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:
    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:
    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:
    WebSocket socket = context.WebSocket; //context -> parameter of MyProcessTask
    Code for receive message:
    ArraySegment<byte> buffer = newArraySegment<byte>(newbyte[1024]);
    //receive data from Client
    WebSocketReceiveResult result = await socket.ReceiveAsync(
    buffer, CancellationToken.None);
    Code for send message:
    //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:
    <%@PagevalidateRequest="false"%> 
  • Or at application level as:
     <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:

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).

<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.

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:

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.

<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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here