Let's Explore ASP.NET Core 1.0 briefly

Rajnilari2015
Posted by in ASP.NET Core category on for Beginner level | Points: 250 | Views : 694 red flag

In this article we will explore the next version of ASP.net which is ASP.NET Core 1.0 (a.k.a. ASP.NET 5).


 Download source code for Let's Explore ASP.NET Core 1.0 briefly

Introduction

The Visual Studio Blog announced on June 27, 2016, that

We have updated VS 2015 to Updated 3 and also installed .NET Core.

In this article we will explore the next version of ASP.net which is ASP.NET Core 1.0 (a.k.a. ASP.NET 5).

What is ASP.NET Core 1.0?

Asp.net Core1.0 is the next version of Asp.net which is 5.0. It is open source and cross-platform framework (supports for Windows, Mac and Linux) suitable for building cloud based internet connected applications like web apps, IoT apps and mobile apps.

Asp.net Core has made itself independent of System.Web.dll and is heavily based on the modular NuGet packages. The inclusion of Nuget Packages will make the applications to be optimized as we need to include only those packages that we need. The benefits includes

  1. Better performance gain
  2. Secured Application
  3. Improved and reduced servicing
  4. Pay for what you use model

Let's create the Asp.net Core Project Application

OK then... Let's fire us VS 2015 and choose Web->Asp.net Core Web Applications(.Net Core). Choose the target Framework as .Net Framework 4.6.1

Click on "OK" button to get the next screen

ASP.NET Core 1.0 includes only Web API and MVC but not SignalR or Web Pages yet. We choose the Web Application and Click "OK" button and here is our "Welcome Screen"

Let's examine Application Structure

(A) Program.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;

namespace Example1
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var host = new WebHostBuilder()
                .UseKestrel()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseIISIntegration()
                .UseStartup<Startup>()
                .Build();

            host.Run();
        }
    }
}

The Main() method uses WebHostBuilder(). It is use to build up the HTTP pipeline via webHostBuilder.Use() chaining it all together with WebHostBuilder.Build() by using the builder pattern. It is available within the Microsoft.AspNet.Hosting namespace.

The purpose of the Build method is to build the required services and a Microsoft.AspNetCore.Hosting.IWebHost which hosts a web application.

The web hosting environment uses Kestrel, a cross-platform web server.

UseContentRoot specifies the content root directory to be used by the web host. It's signature is

public static IWebHostBuilder UseContentRoot(this IWebHostBuilder hostBuilder, string contentRoot);

UseIISIntegration configures the port and base path the server should listen on when running behind AspNetCoreModule. The app will also be configured to capture startup errors. WebHostBuilder uses the UseIISIntegration for hosting in IIS and IIS Express.

UseStartup specifies the startup type to be used by the web host.

The Startup class is the place where we define the request handling pipeline and where any services needed by the app are configured. The Startup class must be public. It's general methods are as under

The Build and Run methods build the IWebHost that will host the app and start it listening for incoming HTTP requests.

(B) Startup.cs

public Startup(IHostingEnvironment env)

public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
        .AddEnvironmentVariables();

    if (env.IsDevelopment())
    {
        // This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
        builder.AddApplicationInsightsSettings(developerMode: true);
    }
    Configuration = builder.Build();
}

Here we are adding the various application settings files.

public void ConfigureServices(IServiceCollection services)

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddApplicationInsightsTelemetry(Configuration);

    services.AddMvc();            
}

ConfigureServices defines the services used by the application like ASP.NET MVC Core framework, Entity Framework Core, CORS,Logging, MemoryCaching etc.

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    app.UseApplicationInsightsRequestTelemetry();

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseBrowserLink();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }

    app.UseApplicationInsightsExceptionTelemetry();

    app.UseStaticFiles();

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

Configure method defines the middleware in the Http request pipeline. The software components that are assembled into an application pipeline to handle requests and responses are the middlewares.

E.g. in the above code,UseExceptionHandler is a middleware. It is added as a middleware to the pipeline that will catch exceptions, log them, reset the request path, and re-execute the request.

For more information about middlewares, please visit here.

(C) appsettings.json

{
  "ApplicationInsights": {
    "InstrumentationKey": ""
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  }
}

It contains information about the application settings. If we need to configure the application seetings, that should be done here.

(D) project.json

{
  "dependencies": {
    "Microsoft.NETCore.App": {
      "version": "1.0.0",
      "type": "platform"
    },
    "Microsoft.ApplicationInsights.AspNetCore": "1.0.0",
    "Microsoft.AspNetCore.Diagnostics": "1.0.0",
    "Microsoft.AspNetCore.Mvc": "1.0.0",
    "Microsoft.AspNetCore.Razor.Tools": {
      "version": "1.0.0-preview2-final",
      "type": "build"
    },
    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.0",
    "Microsoft.AspNetCore.StaticFiles": "1.0.0",
    "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0",
    "Microsoft.Extensions.Configuration.Json": "1.0.0",
    "Microsoft.Extensions.Logging": "1.0.0",
    "Microsoft.Extensions.Logging.Console": "1.0.0",
    "Microsoft.Extensions.Logging.Debug": "1.0.0",
    "Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.0",
    "Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0"
  },

  "tools": {
    "BundlerMinifier.Core": "2.0.238",
    "Microsoft.AspNetCore.Razor.Tools": "1.0.0-preview2-final",
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final"
  },

  "frameworks": {
    "netcoreapp1.0": {
      "imports": [
        "dotnet5.6",
        "portable-net45+win8"
      ]
    }
  },

  "buildOptions": {
    "emitEntryPoint": true,
    "preserveCompilationContext": true
  },

  "runtimeOptions": {
    "configProperties": {
      "System.GC.Server": true
    }
  },

  "publishOptions": {
    "include": [
      "wwwroot",
      "Views",
      "Areas/**/Views",
      "appsettings.json",
      "web.config"
    ]
  },

  "scripts": {
    "prepublish": [ "bower install", "dotnet bundle" ],
    "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
  }
}

It contains the project dependencies. E.g. the line "Microsoft.AspNetCore.Server.Kestrel": "1.0.0" indicates that Kestrel is used as a dependency to the application.

Another middleware that is use as a project dependency is Microsoft.VisualStudio.Web.BrowserLink.Loader

(E) web.config

As opposed to the previous versions, it is recommended to write our application specific seetings in the appsettings.json file and not in the web.config

(F) _ViewImports.cshtml

_ViewImports.cshtml provides namespaces which can be used by all other views

@using Example1
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@inject Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration TelemetryConfiguration

Let's create and run our very first application in Asp.net Core

Add an action to the HomeController.cs file

public IActionResult Welcome2AspDotNetCore()
{
    ViewData["Message"] = "Welcome to Asp.net Core 1.0 - Niladri";

    return View();
}

Add a corresponding view Welcome2AspDotNetCore.cshtml

@{
    ViewData["Title"] = "Asp.Net Core 1.0 - First Application";
}
<h2>@ViewData["Title"]</h2>
<h3>@ViewData["Message"]</h3>

<p>HAPPY LEARNING  - Asp.Net Core 1.0</p>

Add a link in _Layout.cshtml

<div class="navbar-collapse collapse">
    <ul class="nav navbar-nav">
        <li><a asp-area="" asp-controller="Home" asp-action="Index">Home</a></li>
        <li><a asp-area="" asp-controller="Home" asp-action="About">About</a></li>
        <li><a asp-area="" asp-controller="Home" asp-action="Contact">Contact</a></li>
        <li><a asp-area="" asp-controller="Home" asp-action="Welcome2AspDotNetCore">Welcome 2 Asp.Net Core 1.0</a></li>
    </ul>
</div>

Finally run the application

N.B.~At the time of writing the article, the Asp.net Core is not Available for VB.net, Visual C++ or Visual F# language

References

  1. ASP.NET home repo
  2. Introduction to ASP.NET Core

Conclusion

In this introductory article, we have learnt about the basic stuffs regarding Asp.net Core 1.0. Hope we all have enjoyed. Thanks for reading.Zipped file attached.

Important Note: It is very very lightweight.

Recommendation
Read Let's Explore Diagnostics in ASP.NET Core 1.0 after this article.
Page copy protected against web site content infringement by Copyscape

About the Author

Rajnilari2015
Full Name: Niladri Biswas (RNA Team)
Member Level: Platinum
Member Status: Member,Microsoft_MVP,MVP
Member Since: 3/17/2015 2:41:06 AM
Country: India
-- Thanks & Regards, RNA Team


Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)