Page 13 - MSDN Magazine, July 2017
P. 13

references shorter. The following code is enough to serve plain HTML views to browsers. It should be noted, though, that it doesn’t support some more advanced features, including data annotations for form validation and tag helpers:
public void ConfigureServices(IServiceCollection services) {
var builder = services.AddMvcCore(); builder.AddViews(); builder.AddRazorViewEngine();
}
however, provides a default route that serves most of the common scenarios. To enable the default route, you can proceed like this:
public void Configure(IApplicationBuilder app) {
app.UseMvcWithDefaultRoute();
}
The default route is defined as follows and, as you can see, it’s nothing more than the old familiar route configuration of classic ASP.NET MVC:
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
InclassicASP.NETMVC,aroutelessapplicationmakeslittlesense as it would be quite problematic to invoke any behavior from the out- side.InASP.NETMVCCore,instead,routesworkside-by-sidewith the terminating middleware—the Run method of IApplicationBuilder:
public void Configure(IApplicationBuilder app) {
app.UseMvc(routes => { });
// Terminating middleware app.Run(async (context) => {
await context.Response.WriteAsync( "No configured routes here.");
}) }
Given the preceding code, the application has no configured routes. However, it still reacts to any call by displaying a message through the terminating middleware. In other words, you can list your routes first and then use the terminating middleware as a sort of catch-all route that gently informs about any mistyped or misunderstood URLs.
MVC Controllers
Routing is the first step of the longer process that takes an HTTP request to produce a response. The ultimate result of routing is identifying the controller/action pair that will process any requests not mapped to a physical static file. In ASP.NET Core a controller is the same as it was in classic ASP.NET, namely a class that encap- sulates the HTTP context of the request and takes action. The work of a controller is governed by a system component known as the action invoker (see Figure 1). The action invoker isn’t a new item in the overall architecture of ASP.NET MVC as it was part of the architecture since the early days of classic ASP.NET MVC.
The action invoker injects the HTTP context into the controller’s space and the code running within the controller can access it through the handy HttpContext property. To facilitate the process in classic ASP.NET MVC, any controller class must inherit from a base class that contains all the necessary plumbing. In ASP.NET Core, inherit- ing a controller from a common base class is no longer necessary. A controller class can be a plain old C# object (POCO), as simple as this:
public class HomeController {
// Some code here
}
A POCO controller is a class that can map incoming requests to HTML views, but has no dependency on the HTTP context. In particular, this means that you can’t inspect the raw data being posted, including query string and route parameters. The context information, however, is available as a separate plug-in that you attach only to the controllers where you need it. Ultimately, this is anothergoodexampleoftheextremegranularityoftheASP.NET Core framework. As an example, let’s see what’s required to access
July 2017 9
Likewise, this configuration won’t let your controller methods return formatted JSON data. However, you need one extra line to add that capability, as well:
builder.AddJsonFormatters();
It’s worth noting that some of the services the call to AddMvc auto- matically enables are useful to have, though not strictly necessary, only if you’re exposing a Web API. The services you might want to get rid of are API Explorer and Formatter Mappings and, to some extent, CORS.
Enabling the MVC Service
Adding a service to the pipeline isn’t enough: You also have to con- figure it. This typically happens in the Configure method of the startup class via a method that conventionally takes the name of UseXxx where Xxx is the nickname of the service:
public void Configure(IApplicationBuilder app) {
app.UseMvc(); }
At this point, everything in MVC is completely set up and ready to go except conventional routing. If you decide to go with attri- bute routing, then you’re done. Otherwise, for the MVC service to be effective, you must list the routes the application will recognize and handle. A route is a URL template mapped to a pair made of controller and action names. You can add as many routes as you wish and of nearly any shape you like them to be. ASP.NET MVC,
Requested URL
Routing
Action Invoker Authorization Filters Resource Filters
Model Binding Action Filters Exception Filters
Result Filters
Response
Action
Result
Figure 1 A Request Flowing Through the ASP.NET Environment msdnmagazine.com























































   11   12   13   14   15