Page 15 - MSDN Magazine, May 2017
P. 15
traditional ASP.NET developer, it might be shocking to find that even the use of the MVC application model must be explicitly declared and enabled. However, this fact gives the measure of how seriously modularization is taken in ASP.NET Core:
public void ConfigureServices(IServiceCollection services) {
services.AddMvc();
}
In the method Configure, you configure any previously requested services. For example, if you requested the ASP.NET MVC service, then in Configure you can specify the list of supported routes. Note thatyoualsoneedanexplicitcalltoenabletheinternalWebserverto serve static files, including common files such as jQuery and Bootstrap:
public void Configure(IServiceCollection services) {
app.UseStaticFiles(); app.UseMvcWithDefaultRoute(); ...
}
The startup class is also the place where you configure the middleware of the application. Middleware is a new term that has a significant conceptual overlap with the HTTP modules of current ASP.NET. In ASP.NET Core, the middleware works as shown in Figure 3.
In ASP.NET Core, creating an effective file server is easier than ever and more effective than ever.
You can register chunks of code that have a chance to pre- and post-process any incoming request, meaning that each middle- ware can register code that runs before or after the terminating middleware—the method Run in the Configure method of the startup class. The overall model is similar to the old ISAPI model of IIS. Here’s some sample middleware:
app.Use(async (httpContext, next) => {
// Pre-process the request
// Yield to the next middleware await next();
// Post-process the request });
A middleware is a function that takes an HttpContext object and returns a Task. The list of middleware components ends with theRunmethod.ComparedtothecurrentASP.NETpipeline,the ASP.NET Core pipeline is bidirectional and fully customizable. Moreover, it’s empty by default.
Super-Simple Web Services
It’s understood that without a Run method in the pipeline, no requests will ever produce a response. At the same time, a Run method is all you need to produce a response. This shows how short the pipeline can be in an ASP.NET Core application. In ASP.NET WebForms and MVC, many things happen before your own code runs for each request. Resolving a controller method, for example, is quite a long procedure that involves an entire subsystem centered
msdnmagazine.com
on the action invoker. The Run method, instead, is a direct call that immediately follows the receipt of the request.
Suppose you want to create a file server that owns a list of image files (say, flags) and returns a properly sized image based on some input parameters or device properties. In today’s ASP.NET, the fastest option is probably writing an ad hoc HTTP handler—a class created by implementing the IHttpHandler interface mapped to a fixed URL route. An HTTP handler is faster than an ASPX endpoint and MVC controller action because of the slimmer pipeline. It also has a smaller footprint than a Web API endpoint because it doesn’t requireasecondOWINpipelineontopofthebasicASP.NETpipeline. (This isn’t the case when a Web API solution is hosted outside IIS.)
In ASP.NET Core, creating an effective file server is easier than ever and more effective than ever. All you do is craft the additional logic (that is, resize/retrieval) and bind it to the Run method of the ConfigureServices method:
public void Configure(IApplicationBuilder app) {
app.Run(async (context) => {
var code = context.Request.Query["c"];
var size = context.Request.Query["s"];
var file = FindAndResizeFlag(code, file); await context.Response.SendFileAsync(file);
});
}In the example, I assume to have some custom logic to find a server file name that matches provided parameters, and then I serve it back to the caller via the Response object. No other code, either visible or invisible, is required. Frankly, it couldn’t really be easier than this.
Whatever your gut feeling is about ASP.NET Core, whether you’re skeptical or enthusiastic about it, ASP.NET Core provides a unique capability you won’t find on any ASP.NET platform: creating super-simple minimal Web services. At the same time, the same infrastructure that lets you build super-simple Web ser- vices is the best guarantee that any requests can be served with the minimum overhead that’s legitimately possible.
Wrapping Up
To be a productive ASP.NET Core developer, you only need to be familiar with an application model more modern than WebForms: thismeansASP.NETMVCorthesingle-pageapplicationmodel.In spiteoftheappearances,mostofthebreakingchangesofASP.NET Core are in the runtime environment. Understanding the hosting model and the middleware is enough to make sense of the new plat- form. In the end, it’s still about creating controllers and rendering Razor views. A few common things like authentication, logging and configuration will need a different API, but learning that only takes awhile.AsIseeit,thechallengeisfindingwhat’sinitforyou. n
Dino Esposito is the author of “Microsoft .NET: Architecting Applications for the Enterprise” (Microsoft Press, 2014) and “Modern Web Applications with ASP.NET” (Microsoft Press, 2016). A technical evangelist for the .NET and Android platforms at JetBrains, and frequent speaker at industry events worldwide, Esposito shares his vision of software at software2cents@wordpress.com and on Twitter: @despos.
thanks to the following Microsoft technical expert for reviewing this article: James McCaffrey
May 2017 11