ASP.NET Core in 10 minutes

With the recent release of version 2.0, ASP.NET Core is now more ready and complete. ASP.NET Core is an open-source framework for building web apps and services, IoT apps and mobile backends. It is a cross-platform ecosystem, meaning that you can develop, test and run it on Windows, macOS, and Linux. It is also designed to unify building web apps and APIs, as well as integrate with modern client-side frameworks like Angular and React.js. Essentially, ASP.NET Core is lightweight and ships entirely as NuGet packages, thus allowing code optimization using only needed packages. Performance wise, it has proven to be one of the fastest frameworks on the planet.

If you consider yourself an avid web developer and have been wondering when to adopt ASP.NET Core, trust me, the time has come. You will surely be impressed by the architectural changes made to the new platform and how this new ecosystem differs from the older ASP.NET web development framework. If you are coming from such a background, this article will definitely help you get started.

Wait, what is .NET Core ??

There are a lot of. NETs out there in the world today. We have .NET Framework, .NET Core, Mono, Xamarin and.Net Standard… Don’t panic. These are all just different flavors created for different environments. The .NET Standard provides the spec which all should implement, meaning that .Net Standard is the intersection of all those runtimes. .NET Core implements it and is made to run on Linux, Mac, and Windows, allowing other frameworks like ASPNET to be cross platform.

An ASP.NET Core application can target either the .NET Core or .NET Framework runtime, .NET Framework can be only targeted on Windows machines. Apps can be developed using Visual Studio for Mac or Windows, or Visual Studio Code for Mac, Windows, and Linux.

See Choosing between .NET Core and .NET Framework for more details.

Project Templates and Folder Structure

There are several default templates that ship with Visual Studio and you can use while creating a new ASPNET Core application. I suggest you try each one and navigate through the folder structure, Startup.cs and Program.cs to see the difference.

Creating a new ASPNET Core project on Visual Studio for Windows

Below is an ASPNET Core app with MVC, you can also choose to create a project without MVC.

You can see above a new wwwroot folder introduced as the root folder for serving static files.

The Program class

You can notice a new Program.cs in the project. That’s because the ASP.NET Core application is now a console app that creates a web server in its Main method.


using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;

  public class Program
    {
        public static void Main(string[] args)
        {
            BuildWebHost(args).Run();
        }

        public static IWebHost BuildWebHost(string[] args) =
            WebHost.CreateDefaultBuilder(args)
                .UseStartup()
                .Build();
    }

The Startup class

ASP.NET Core apps also require a Startup class. You can define separate Startup classes for different environments, and the appropriate one will be selected at runtime. The Startup class constructor can accept dependencies that are provided through dependency injection. The Startup class must include a Configure method and can optionally include a ConfigureServices method, both of which are called when the application starts. ConfigureServices, if present, is called before Configure.


public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddDbContext(options =
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

    services.AddMvc();

}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
      
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }

    app.UseStaticFiles(); 

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

Goodbye to Web.config

In the past, we used Web.config for application configuration and settings. Well not anymore! ASP.NET Core now uses a new model for handling simple name-value configuration. The configuration system allows you to store option values anywhere you want by default in an appsettings.json file.

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)...",
  },  
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning",
      "Microsoft": "Warning",
      "System": "Warning"
    }
  }
}

appsettings.json

Now to use these settings in your code.

  public Startup(IConfiguration configuration)
  {
    var builder = new ConfigurationBuilder()              
      .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)               
 
    // Retrieve values
    var connectionString = Configuration.GetConnectionString("DefaultConnection");
    var loggingOptions = Configuration.GetSection("Logging");

     Configuration = configuration;
   }

Startup.cs

The Web.config is strictly used to configure IIS only in case the app is being hosted on Windows. You might not be convinced yet and wondering about how to register Handlers and Modules well the thing is that Modules, Handlers, Global.asax.cs and the application life cycle are also gone.

Handlers and Modules are Gone too

The roles of both modules and handlers is taken over by a new thing called Middlewares. There is no application life cycle in ASP.NET Core and the order in which responses are processed by middleware differs from the order used by modules. This could make your ordering decision more challenging.

ASP.NET Core ships with a bunch of middleware components like Authentication, Routing, CORS, Response Compression and others. Middleware is generally encapsulated in a class and exposed with an extension method. Middleware is used in Configure function in Startup.cs

The below code is taken from here.



//Class defining the middleware RequestCulture
public class RequestCultureMiddleware
    {
        private readonly RequestDelegate _next;

        public RequestCultureMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public Task Invoke(HttpContext context)
        {
            var cultureQuery = context.Request.Query["culture"];
            if (!string.IsNullOrWhiteSpace(cultureQuery))
            {
                var culture = new CultureInfo(cultureQuery);

                CultureInfo.CurrentCulture = culture;
                CultureInfo.CurrentUICulture = culture;

            }

            // Call the next delegate/middleware in the pipeline
            return this._next(context);
        }
    }

//Extension method to expose the RequestCulture through IApplicationBuilder
public static class RequestCultureMiddlewareExtensions
    {
        public static IApplicationBuilder UseRequestCulture(
            this IApplicationBuilder builder)
        {
            return builder.UseMiddleware();
        }
    }

//The following code calls RequestCulture middleware from Configure:
public class Startup
{
    public void Configure(IApplicationBuilder app)
    {
        app.UseRequestCulture();  //RequestCulture is the middleware

        app.Run(async (context) =>
        {
            await context.Response.WriteAsync(
                $"Hello {CultureInfo.CurrentCulture.DisplayName}");
        });

    }
}

Razor Pages

Razor pages are a new feature of ASP.NET Core. Just like old days, you can now use the @page directive to make a .cshtml file that handles requests directly without going through a controller. You can develop a full site with using the MVC framework and only using pages, just like old ASP.NET Web Forms. A sample razor page would look like this.


@page
@model IndexModel
@using Microsoft.AspNetCore.Mvc.RazorPages

@functions {
  public class IndexModel : PageModel
  {
    public string Message { get; private set; } = "In page model: ";

    public void OnGet()
    {
      Message += $" Server seconds { DateTime.Now.Second.ToString() }";
    }
  }
}





<h2>In page sample</h2>






  @Model.Message


More Changes

HttpContext has changed

HttpContext has significantly changed in ASP.NET Core from System.Web.HttpContext to the new Microsoft.AspNetCore.Http.HttpContext. More

Tag Helpers are gone

Remember the @Html. helpers ?

@using (Html.BeginForm())
{  

    
<div>
        @Html.LabelFor(m => p.Name, "Name")
        @Html.TextBoxFor(m => p.Name)
    </div>


    <input type="submit" value="Save" />
}

They are now replaced with Tag helpers like below


<form asp-controller="Register" asp-action="Create" method="post">
         
     
<div>
       <label asp-for="Name">Name</label>
       <input asp-for="Name" />
     </div>


    <input type="submit" value="Save" />
</form>

There is a lot more to the new framework and all the details are very well documented on the official site. In this article, I tried to cover the most important changes relevant to someone using older versions of ASP.NET. There is a lot more new features targeting client-side development and amazing integration with powerful tools like WebPack, Gulp and Grunt. Don’t forget to check them out.

All content is taken from Microsoft Docs.

Cheers!

This entry was posted in C# and tagged , , , , , , , , , . Bookmark the permalink.

Leave a reply

*