Understanding Asp.Net Core 1.1 & Visual Studio 2017

I just installed the new Visual Studio 2017 community edition and so far the experience is awesome. Lets create an Asp.net Core project and see the results.

I like to create empty projects so that i can add everything from the scratch. This way i feel more in control and understand the inner details of whats going on in the codes and how to get hold of my applications.

Creating a new project is not much different then the previous versions of Visual Studio and .Net frameworks. After selecting Asp.net Core Web Application and naming my applications as “Venues”, I have to select a template to start with.

I have three different type of templates to start with. Empty template will leave me on my own with bootstrapping of my application. Web API starts a project pre-configured to create APIs, all the related Middlewares are installed and added appropriately. Web Application installs a detailed application with most of the things in place to be used as it is e.g., Login, Logout, Register and Identity frameworks.

As I am moving forward with a blank project, my selection is “Empty” template.

A blank project is created for me, lets look at the details of files added in the project.

Connected Services

I can configure application insights with Azure account using connected services. There are other connected services but most of them are not regularly used. I will explore them later in some other blog.

Dependencies

My project is dependent on NuGet packages as well as .Net Core SDK. I can see all of dependencies listed under dependencies.

Properties

There is only one file under properties named as “launchSettings.json”. Asp.net Core rely on JSON configuration files to keep the configurations lighter and easier to modify. Following are the contents of “launchSettings.json” file.

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:54937/",
      "sslPort": 0
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "VenuesApp": {
      "commandName": "Project",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      },
      "applicationUrl": "http://localhost:54938"
    }
  }
}

Most of the elements of the JSON file are configurations that were previously provided via web.config files. “launchSettings.json” is helpful to create two or more development environments to test project in different scenarios.

wwwroot

wwwroot folder contains all the static files for the project. Currently its empty as the project has no content right now.

Program.cs

This is where the interesting part begins. Previous asp.net mvc projects had global.asax files from where the Application_start method was used to bootstrap an application. Asp.net Core has redefined the bootstrapping and provided a static main method just like any other console application or windows form application. Program.cs contains the static main method as an entry point for the application. Following are the default contents of program.cs file.


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

main method is building a web host and running the host. Host is also responsible to configure a server. In this case the server being configured and used is Kestrel.

ContentRoot is the directory where Asp.net Core will look forward for the content files e.g., razor views.

If I want my application to work with IIS, i need to use .UseIISIntegration() with the .UseKestrel(). Kestrel is a server which implemented IServer interface but IIS is not the same. Kestrel is written specifically to work behind the proxies. UseIISIntegration() asks IIS to work as reverse proxy server. So kestrel will still create the web server and host the files behind IIS.

Startup class configures the pipeline that is responsible to handle the requests and pass through different channels and Middlewares to get the appropriate response.

Startup.cs

Asp.net Core depends on a start class conventionally to prepare the request pipeline. Following are the default contents of Startup class.

    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("Hello World!");
            });
        }
    }

configure method accepts three parameters app, env and a loggerFactory. app can be used to add multiple Middlewares in the pipeline and running the application. env contains the information related to the current loaded environment for the application. loggerFactory is a default logger provided by the Asp.net Core to log the details of applications for development proposes.

All of the three arguments are resolved using the default dependency injection used by Asp.net Core. It’s easy to identify that app.UseDeveloperExceptionPage() is a middleware only be loaded if the application is in development environment.

app.Run creates an anonymous task using lambda expression calling it asynchronously and wait for its completion. The anonymous task writes “Hello World!” on the response. The execution of pipeline is finished and “hello world!” is written on the screen.

Compile the project, run it in IIS Express and the results are

Advertisements

2 thoughts on “Understanding Asp.Net Core 1.1 & Visual Studio 2017

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s