Page 12 - MSDN Magazine, July 2017
P. 12
Cutting EdgE DINO ESPOSITO Finding the Cheese in ASP.NET Core
Do you know the fable of two mice, two little boys and their cheese? It’s not an Aesop’s classic fable, but it’s a modern account full of motivational points written some 20 years ago by Spencer Johnson under the title, “Who Moved My Cheese?” The story is a metaphor for change and the way we should cope with and adapt to it. I dare say that the first, perhaps unconfessed, sentiment that some devel- opersfeelaboutASP.NETCoreisdismay—likeinthisfablewhen the characters reach out to the cheese station only to find it empty.
Who moved my cheese, then? The good news is that there’s still a lot of cheese around for every ASP.NET Core developer—probably more cheese than ever—but some of it’s no longer in the corridor of the development maze where it was before. Out of metaphor, that means that some common ASP.NET MVC tasks require dif- ferent programming skills and sometimes a different approach. This month, I’ll pick up on actions such as registering the Model- View-Controller (MVC) framework, defining core routes and controllers, and passing global data around.
It’s No Longer MVC By Default
A new empty ASP.NET Core project you create in Visual Studio 2015 or Visual Studio 2017 is primarily a Web project, meaning that it produces a server front end for an HTTP-enabled client to call. As pointed out in my May 2017 column (msdn.com/magazine/mt808498), ASP.NET Core is now great at setting up mini-Web servers devoid of the overhead and sophistication of a full Web site. However, ASP.NET Core isn’t limited to that and still provides plenty of oppor- tunities to arrange full Web sites through the familiar programming pattern of routes, controllers and views. ASP.NET Core, though, requires an extra initial step before you can start adding routes and creating controllers and lets you register routes through a slightly dif- ferent approach than in classic ASP.NET MVC. Let’s see how it works.
As mentioned, ASP.NET Core is a plain Web front end based on two main segments of code: routing and application model. The transition between segments isn’t particularly visible to developers and takes place in the MvcRouteHandler service (see bit.ly/2osQOcs). Once the control leaves the routing repository, the MVC application model can be enabled explicitly. If not, any requests end up being processed in the terminating method of the ASP.NET Core middle- ware. To add the MVC service to the ASP.NET container, you add a line of code to the ConfigureService method of the startup class:
public void ConfigureServices(IServiceCollection services) {
services.AddMvc();
}
Note that the code requires a reference to an additional package that the IDE of choice (Visual Studio) typically offers to restore for you. The parameter-less version of the AddMvc method uses all default settings for the MVC route handler service. Most of the time, you don’t need to change any of those default settings, but surely situations might occur where you just need to make changes.AsecondoverloadoftheAddMvcmethodletsyouselect ad hoc options. The second overload receives an instance of the MvcOptions class as an argument. Here’s an example:
services.AddMvc(options => {
options.ModelBinderProviders.Add(new MyDateBinderProvider());
options.SslPort = 345; });
The MvcOptions class is a container of configuration parameters for features you might want to customize in the MVC framework. For example, the previous code snippet adds a new model binder that changes the standard way in which posted dates are mapped to .NET date objects. You can assume that the MyDateBinderProvider class here adds the ability to parse ad hoc strings into valid DateTime objects. In addition, the example specifies the SSL port to be sniffed when any controller class is decorated with the RequireHttps- Attribute. The list of options you can configure isn’t limited to the three examples here. The full list can be found at bit.ly/2oK7ETs.
It’s worth noting that the AddMvc method is an umbrella method under which a lot of finer-grained services are initialized and added to the pipeline. Because of this, the effect of AddMvc on the memory footprint of the whole application might need some forethought. Not that AddMvc bloats the runtime, but it does quite a few things internally and atomically enables quite a few services. In addition to the core services of the MVC application model, such as routes and controllers, it also enables authentication and authorization, tag helpers, URL resolution helpers, default media type mappings, data annotations, and cross-origin resource sharing (CORS). Furthermore, AddMvc sets up the service to process action results as HTML views and JSON streams and registers the Razor view engine into the MVC system.
Cutting Down the List of Default MVC Services
Especially if you’re hosting the application in some sort of cloud configuration, you might want to be very stingy about resources and have the application reference nothing but the bare metal of the ASP.NET framework. Calling AddMvc might give much more than you need sometimes. Let’s see how to make the list of
8 msdn magazine