Introducing the ASP.Net Core MVC framework

The ASP.Net Core MVC framework enables you to build applications that are loosely-coupled, responsive, fast and easier to test and maintain

Introducing the ASP.Net Core MVC framework
Joydip Kanjilal

ASP.Net Core MVC is a cross-platform web application development framework that leverages the benefits of the ASP.Net Core runtime while at the same time enabling you to design applications that are testable and maintainable and can be developed and deployed over multiple platforms. Note that MVC Core doesn't need IIS for hosting — you can host MVC Core applications in Kestrel or they can even be self-hosted. ASP.Net MVC Core is open source, has built-in support for dependency injection and is extensible. Note that the MVC framework helps you to isolate the concerns in your applications and build applications that are easier to test and maintain.

The salient features in MVC Core include routing, model binding, model validation, dependency injection, filters, areas, web APIs, strongly typed views, tag helpers, and view components. Let’s now take a look at each of these features in brief. We will revisit each of these in later posts here.

Routing

The routing engine of ASP.Net Core MVC is built on top of the ASP.Net Core routing engine. You now have support for routing in two different ways - the convention-based routing feature and the attribute driven routing feature. In the former, you can define URL formats for your application globally as shown below.

routes.MapRoute(name: "Default", template: "{controller=Home}/{action=Index}/{id?}");

Attribute routing enables you to specify routing information by applying attributes on your controllers and action methods as shown in the code snippet given below.

[Route("api/customers")]
public class CustomersController : Controller
{
  [HttpGet("{id}")]
  public IActionResult GetCustomer(int id)
  {
    //Write your usual code here
  }
}

Model validation

You can decorate your model objects using attributes to perform model validation in ASP.Net MVC Code. The following code snippet illustrates how you can take advantage of data annotations to decorate your model.

using System.ComponentModel.DataAnnotations;
public class CustomerViewModel
{
    [Required]
    [FirstName]
    public string FirstName { get; set; }
    [Required]
    [LastName]
    public string LastName { get; set; }
}

Note that the validation attributes are checked both at the client side and also at the server side.

public async Task<IActionResult> SaveData(CustomerViewModel model, string returnUrl = null)
{
    if (ModelState.IsValid)
    {
      // Write your code here to save data
    }
    // Error occurred
    return View(model);
}

Dependency injection

Since ASP.Net MVC Core is built on top of ASP.Net Core, it inherits the dependency injection capabilities of ASP.Net Core as well. Support for dependency injection and the service locator framework is in-built in ASP.Net Core. There are four modes in which a type can be injected. These include: Singleton, Scoped, Transient and Instance.

ASP.Net MVC Core enables you to inject dependencies using constructors to the controller classes. You can also inject dependencies in the view files using the @inject directive.

You can register a type in the ConfigureServices method of the Startup.cs file as shown below.

public void ConfigureServices(IServiceCollection services)
{
   services.AddMvc();
   services.AddSingleton<ILoggingService,LoggingService>();
}

Once the type is registered with the framework, you can inject the type using the constructor of a controller as shown below.

public class CustomerController : Controller
{
   private ILoggingService logger;
   public CustomerController(ILoggingService logger)
   {
      this.logger = logger;
   }
}

Strongly typed views

ASP.Net Core MVC provides support for strongly typed views. So, your razor views can be strongly typed as well.

@model IEnumerable<Customer>
<ul>
    @foreach (Customer c in Model)
    {
        <li>@c.FirstName</li>
        <li>@c.LastName</li>
    }
</ul>

Support for Tag helpers

Tag helpers are used to enable server side code create and render HTML elements. You have many in-built Tag helpers in ASP.Net Core MVC. You can also create your custom Tag helper as well. The in-built Tag helpers can be used for creating forms, loading assets, etc.

Support for Web API

ASP.Net MVC Core provides excellent support for building light-weight services using Web API that can run over HTTP. ASP.Net Web API is a framework that you can make use of to build light-weight web services that use HTTP as the protocol. Web API provides in-built support for content negotiation, formatters and cross-origin resource sharing (CORS).

Cloud Ready

With MVC Core, you can now build and configure your applications to be cloud-ready. Building and deploying application for the cloud is now seamless with excellent support for environment-based configuration. In essence, you now have support for a cloud-ready environment-based configuration system. This helps in saving the time you otherwise have to waste due to errors that occur during deployment.

I will discuss on how we can build applications using the MVC Core framework in a later post here.

Copyright © 2017 IDG Communications, Inc.