Infopulse - Expert Software Engineering, Infrastructure Management Services
Send message Request a call
Send message Please fill in this quick form and we will send you a free quote shortly.
* Required fields
Request a call Please fill in this quick form and we will call you back shortly.
* Required fields
Subscribe to Infopulse Newsletter Please fill in this quick form to be among the first to receive our updates.
* Required fields
Send an email to Dmitriy Onykyyenko Please fill in this quick form to contact our expert directly.
* Required fields
Read the rest of the Case Study Don't miss the most interesting part of the story!
Submit this quick form to see the rest and to freely access all case studies on our website.
* Required fields

Microsoft web-framework evolution: ASP.NET vNext

Backgrounds of change

The news of the ASP.NET vNext release spread on the Internet quite fast, announcing the most interesting innovations offered in the new version. The new framework is the renewed and rebranded ASP.NET MVC 6, which is being marketed as a real novelty among Microsoft (MS) web-frameworks. To fully understand the importance of the announced changes in vNext, we must look at the current implementation of web applications within the .NET framework.

A typical ASP.NET MVC application consists of a Global.asax file, in which we extend the HttpApplication class (System.Web) to include the needed kind of Http request processing by configuring separate components of MVC. The Router class (System.Web.Routing) of a typical ASP.NET MVC is an indispensable part of Http request processing, which directs requests to the necessary HttpHandler (MvcRouteHandler in standard operation), which, in its turn, creates a controller factory and launches the pipe for request handling. These components are made to fit the MS web-server – Internet Information Services (IIS), which uses HttpHandlers and HttpContext (access to the http request/ response parameters) to process requests. Being the successor of ASP.NET Web Forms, MVC with its components was meant for deep integration with IIS, which made it impossible to use an alternative web-server for hosting applications. As time went by, this caused increasing criticism from the developer community and it indeed was a hindrance to the development of ASP.NET MVC, which, being an Open source project, is developed at a faster rate than Microsoft develops the updates for System.Web components.

Framework evolution example

An attempt to improve the situation was made as part of Web API project. While shifting from MS WCF framework the developers stopped building RESTful services within the “binding-contract” concept and chose a more convenient approach of MVC, which determined a lot in common with MVC and a fine resembling name of ASP.NET Web Api. As a matter of fact, the developers of the new framework managed to come up with it considering all the drawbacks of ASP.NET MVC described above. The Web Api did not employ directly the System.Web components because it had adapters for HttpContext.Request and HttpContext.Response, that is – abstractions with a renewed structure of HttpRequestMessage and HttpResponseMessage, in which HttpControllerHandler (entry point of Web Api application) transformed the mentioned objects. Also, the dependency on IIS’s HttpHandlers was eliminated by processing requests through a chain of embedded HttpMessageHandlers (System.Net.Http), which were the bases for the renewed stack (filters, dispatchers, delegating handlers, controllers).

Framework evolution example

All these changes made the Web Api application independent of the host and allowed developing it as an OWIN (Open Web Interface). There appeared the key notion of “middleware” – web application components (HttpModules in IIS) and an application delegate, which interacts not with HttpContext, but with a much more abstract set of request/ response parameters in the hash-map of the IDictionary<string,object> type.

Framework evolution example

Despite all the advantages, flexibility, improved extension possibility and a scope of fixed architectural drawbacks, Web Api could not fully substitute MVC because it focused on Single Page Applications (SPA). At the same time there was no collision between the frameworks. Moreover, they could function simultaneously in one web application while using IIS for hosting and could use common Http modules, e.g. for authentication. Nevertheless, the approach discussed above demanded a clear division of responsibilities in an application and consideration of the fact that Web Api and MVC use completely different pipelines for processing requests. The latter complicated developers’ work and caused the ensuing refactoring which resulted in a new version of the framework, named vNext.

ASP.NET vNext template project

The first striking peculiarity of the new web application is the absence of web.config, packages.config and even AssemblyInfo.cs  files.

Framework evolution example

The structure of the solution contains only 2 files:

  • json – project configuration file, which contains dependencies indicating versions of employed packages, parameters of the project assembly, metadata, a list of dependencies for .NET and Core CLR deployment;
  • Startup.cs – entry point, web application class.

This template does not have as many options in the properties of a VS project, as can be found in ASP.NET projects. There are only two tabs: 1) General, containing namespace’s configuration and configuration of a type of application being built; 2) Debugging, containing the number of the port which will host the application.

The project configuration file, project.json, is even more surprising and looks like this.

Framework evolution example

The primary set provides only two keys:

  • dependencies, which indicates dependencies for a project determined by compiling, NuGet Packages and even the source code on disk;
  • configurations, which lists dependencies of a project for specific target environment i.e. .Net or Core CLR.

Such drastic changes in project structure were caused by applying the new Roslyn compiler, which makes it possible in runtime to compile the source code into IL and to execute it at the same time. Roslyn capacities also formed the basis for the new execution environment, namely K Language Runtime (KLR). Currently, only two options of launching a project exist for this environment: .NET Desktop and Core CLR (the Core CLR option in the alpha version is possible only in KLR on Win 8). A project may be assembled using K Versions Manager (KVM)/K Packages Manager (KPM) – command-line tools, which come together with K and allow controlling independently the installed versions of KRE (K Runtime Engine), unpacking applications on the basis of project.json, and launching them. For more information, please refer to github.com/aspnet/home.

ASP.NET vNext web-application structure

The only source code file in a project – Startup.cs – contains a pointer to namespace Microsoft.AspNet.Builder, and a class with a structure, similar to OWIN based applications. The class has one method – Configure, with the input value of IBuilder type. The project can be compiled and launched, but it does not respond in any way, which comes as no surprise, since no middleware has been added. Actually, it responds as “403”, because IIS, having found no request processor, tries to access the file system.

Framework evolution example

The www.asp.net/vnext offers to engage the static Extensions method (UseWelcomePage) to add the simplest Request Handler, but let’s leave that aside since it obscures the peculiarity of functioning of IBuilder interface. Let’s go deeper and look at IBuilder interface definition:

using System;

namespace Microsoft.AspNet.Builder
{
public interface IBuilder
{
IServiceProvider ApplicationServices { get; set; }
IServerInformation Server { get; set; }
RequestDelegate Build();
IBuilder New();
IBuilder Use(Func<RequestDelegate, RequestDelegate> middleware);
}
}

To find our way about the code we have to remember that the notion of “middleware” in OWIN refers directly to Application Delegate, which receives a list of Http request parameters and modifies it, returning the Task.

Func<IDictionary<string, object>, Task>

There was another static Extensions method for OWIN on the level of IAppBuilder interface, which allowed adding middleware by using IOwinContext – a more structured and convenient version of context. It is a little different in vNext now, since it works with HttpContext directly. The HttpContext can be found now in namespace Microsoft.AspNet.Http, and it has no similarity whatsoever to HttpContext from System.Web, just as was the case with the HttpContextBase wrapper in ASP.NET MVC:

public delegate Task RequestDelegate(HttpContext context);

Now, everything becomes clear. RequestDelegate in vNext is the very same OWIN Application Delegate.

To add new middleware to the original realization of the Use method we involve Generic delegate, which contains an embedded RequestDelegate as a parameter. The outer Generic delegate refers to the whole of the further pipeline of Http request processing, and RequestDelegate functions as Http Handler.

To make things clearer, let’s have a look at an example with the added modules:

public void Configure(IBuilder app)
{
app.Use(next =>
httpContext =>
httpContext.Response.WriteAsync(“Executed before all  followers.” + Environment.NewLine)
.ContinueWith(task => next(httpContext)));
app.Use(next =>
httpContext =>
next(httpContext)
.ContinueWith(task =>
httpContext.Response.WriteAsync(“Executed after all followers.” + Environment.NewLine)));
app.Use((httpContext, next) => httpContext.Response.WriteAsync(“Hello world middleware.” + Environment.NewLine));
}

As can be seen from the example, the middleware configuration shows functioning, which is in many ways similar to Delegating Handlers Web Api, wherein we can control the sequence of execution of the further pipeline (the “next” parameter) from the current module. All we have to do is to add Http request handling to lambda expressions, which are directed to Use.

Framework evolution example

As to the OWIN itself, vNext is fully compatible with this interface. The namespace Microsoft.AspNet.Builder contains a class of static extension methods for IBuilder, which create transition adapters between Owin Application Delegate and vNext RequestDelegate.

using AddMiddleware = Action<Func<Func<IDictionary<string, object>, Task>,  Func<IDictionary<string, object>, Task>>>;

public static AddMiddleware UseOwin(this IBuilder builder)
{
….
}

We can use AddMiddleware in our application to provide interaction between OWIN Environment dictionary and vNext HttpContext, relying on the intrinsic implementation of the framework. The extension will allow quite an easy use of OWIN components in the new version of the framework.

One of the key peculiarities to be mentioned is the following: unlike OWIN AppBuilder, the interface of vNext IBuilder has an embedded service locator ApplicationServices, which is initialized by web-server application. It provides access to Web Host Application Level Services.

vNext HttpContext

So far we have covered the application structure. Now let’s look at the new vNext HttpContext. As expected, Request and Response in the context class are declared abstract. HttpContext, as realized by the provided in the package host, Microsoft.AspNet.Hosting, is instantiated by DefaultHttpContext before each instance of middleware chain activation.  The context offers two service locators – ApplicationServices and RequestServices – with corresponding container life cycles. It clearly indicates a more convenient composition of Structure Map on application level compared to previous versions of ASP.NET MVC.

vNext features a new mechanism of context extension by using HttpFeatures. On context interface level it presupposes two sets of methods for obtaining and adding extensions (by wrapping into “object” and “generic wrapper”).

public abstract object GetFeature(Type type);

public abstract void SetFeature(Type type, object instance);

public virtual T GetFeature<T>()
{
return (T)GetFeature(typeof(T));
}

public virtual void SetFeature<T>(T instance)
{
SetFeature(typeof(T), instance);
}

The new version of ASP.NET utilizes this approach for dynamic context formation, starting from the first invocation of HttpContext, wherein Host Application/Server Specific Features are initialized, and up to the point, where some middleware components use request parameters, authentication, caching, working with web sockets. The underlying implementation of Request almost completely uses interfaces defined by Microsoft.AspNet.Builder in order to get the constituents from HttpFeatures only. Thus, context formation allows hiding behind an interface of a component a web-server specific implementation of functionality on the level of a host, not being limited by the HttpContext basic structure.

vNext MVC

The most expected innovation in the application structure is, surely, the joined functionality of ASP.NET MVC and Web Api in one framework, which enables using common pipeline for Http request processing.

Adding of MVC functionality to vNext presupposes employing and configuring two middleware modules:

  • vNext Dependency Resolver with a list of services, which form the vNext MVC stack;
  • Router middleware – MVC router module.

public void Configure(IBuilder app)
{
app.UseServices(services => services.AddMvc());
app.UseMvc(router =>
router.MapRoute(“DefaultHome”,
“{controller}/{action}/{id?}”,
defaults: new { Controller = “Home”, Action = “Index” }));
}

The first module is a set of services, which executes standard MVC components and is used along the whole pipeline to process a request on the level of separate abstractions. It includes Action context providers, controller factory, model binding, View Engine providers, etc. Service description together with DI mapping can be seen in class Microsoft.AspNet.Mvc.MvcServices.cs.

The second module, RouterHandler, is implemented in vNext in the IRouter interface with an async method RouteAsync:

public interface IRouter
{
Task RouteAsync(RouteContext context);
string GetVirtualPath(VirtualPathContext context);
}

By default the interface executes the MvcRouteHandler class. Unlike previous routing versions, which are based on framework-specific functionality (HttpHandler in MVC, DelegatingHandler in Web Api), this one presupposes activating only some interface methods, received from service locator with a set of MVC components. It is this class that is received by ActionContext, which invokes further pipeline of request handling, using IActionInvoker together with ControllerFactory. The major advantage of such approach is obvious – it provides necessary genericity for merging frameworks, which wasn’t possible before.

Another positive change in the new version of MVC is fully asynchronous processing of service methods. The pipe in Web Api is implemented in a similar way. It allows taking out the resource-expecting operations from working pool of web-server stream. And, similarly, MVC has provided only asynchronous controllers in the package.

The major processing unit of Http requests in vNext is Controller from MVC. Post-processing and serialization of execution results is done with the help of IActionResult interface. Functionality of MVC in this respect has basically remained unchanged. As for the main extensions, which proved their worth in Web Api, they are not currently added to vNext pipeline, e.g. defining a formatter by using Content Negotiation services. If a class instance, which does not realize IActionResult, is returned, the JSON-formatter is used by the Controller.

The application configuring mechanism was significantly modified due to transition to a new design pattern. Now, config.json is used instead of web.config. Config.josn is a hierarchical structure of key/value pairs.

Framework evolution example

On the code level, there is a set of utilities from namespace Microsoft.Framework.ConfigurationModel, which merge keys from different configuration sources, for example, parameters of host application launch, transmitted in the K console; pairs of fixed values in project.json and config.json of a web application.

Each of the abovementioned components, as well as those not mentioned here, may become subjects of separate reviews, and they, probably, will. But, taking into consideration, that the list of functional components of the new framework is not finally determined, it will suffice for now to get a basic understanding of the functioning of its main components.

Conclusion

Getting acquainted with the alpha version of ASP.NET MVC vNext makes it possible to say, that there are some very serious changes in store for the developers. The changes are brought about not only by significant refactoring of ASP.NET, but also by the adaptation of the framework to the new Runtime.

Talking about the application, the changes to its inner concepts are fairly limited and will be intuitively understood by developers, who have had experience with OWIN and older versions of ASP.NET MVC.

As for the framework, the most important things to mention are its transition to open web interface and a clear-cut division of responsibilities between host and application. Qualitative renovation of the abstraction set and adding flexible extension opportunities reveal new prospects in web application development.

Useful resources:

Share this blog article:
Subscribe to our Newsletter