How to create an ASP NET Core MVC Web Application using dotnet-cli

NET Core command-line interface (dotnet-cli) is a new NET Core toolset (commands) for developing NET Core Applications. The dotnet-cli toolset provides a list of pre-installed dotnet core project templates from which the user can create various applications as ASP.NET Core MVC Web Application, WPF (Windows Presentation Foundation) application, console application, Windows Form application, and other test projects. The application created with dotnet-cli can be executed on any Windows, Linux, or macOS operating system.

How to create an “ASP.NET Core MVC Web Application”

The user can use the dotnet new “ASP.NET Core Web App (Model-View-Controller)” or the short-form “dotnet new mvc” command from the dotnet-CLI toolset to create a new Core MVC Web Application. The command creates the basic MVC application. The user can also create a Web application with Angular, React, etc, from the list of available templates. You can check the installed templates by using the dotnet new –list command. The command provides a few options that can be applied as a parameter to tweak the output of the command as shown below :

“dotnet new mvc –no-restore”: This command does not restore the project dependencies required by the MVC Web application. Please follow through to read about a few “dotnet new mvc” command usage.

Prerequisite:

NET Core SDK 1.x and above. The current version is .NET Core 5.0 and can be downloaded here.

Command Syntax:

The format of the command is as follows: dotnet new mvc [options]

The details of the available command options can be listed using the –help option as follows:

c:\>dotnet new mvc --help
Usage: new [options]

Options:
  -h, --help          Displays help for this command.
  -l, --list          Lists templates containing the specified name. If no name is specified, lists all templates.
  -n, --name          The name for the output being created. If no name is specified, the name of the current directory is used.
  -o, --output        Location to place the generated output.
  -i, --install       Installs a source or a template pack.
  -u, --uninstall     Uninstalls a source or a template pack.
  --nuget-source      Specifies a NuGet source to use during install.
  --type              Filters templates based on available types. Predefined values are "project", "item" or "other".
  --dry-run           Displays a summary of what would happen if the given command line were run if it would result in a template creation.
  --force             Forces content to be generated even if it would change existing files.
  -lang, --language   Filters templates based on language and specifies the language of the template to create.


ASP.NET Core Web App (Model-View-Controller) (C#)
Author: Microsoft
Description: A project template for creating an ASP.NET Core application with example ASP.NET Core MVC Views and Controllers. This template can also be used for RESTful HTTP services.
This template contains technologies from parties other than Microsoft, see https://aka.ms/aspnetcore-template-3pn-210 for details.
Options:
  -au|--auth                      The type of authentication to use
                                      None             - No authentication
                                      Individual       - Individual authentication
                                      IndividualB2C    - Individual authentication with Azure AD B2C
                                      SingleOrg        - Organizational authentication for a single tenant
                                      MultiOrg         - Organizational authentication for multiple tenants
                                      Windows          - Windows authentication
                                  Default: None

  --aad-b2c-instance              The Azure Active Directory B2C instance to connect to (use with IndividualB2C auth).
                                  string - Optional
                                  Default: https://login.microsoftonline.com/tfp/

  -ssp|--susi-policy-id           The sign-in and sign-up policy ID for this project (use with IndividualB2C auth).
                                  string - Optional

  -rp|--reset-password-policy-id  The reset password policy ID for this project (use with IndividualB2C auth).
                                  string - Optional

  -ep|--edit-profile-policy-id    The edit profile policy ID for this project (use with IndividualB2C auth).
                                  string - Optional

  --aad-instance                  The Azure Active Directory instance to connect to (use with SingleOrg or MultiOrg auth).
                                  string - Optional
                                  Default: https://login.microsoftonline.com/

  --client-id                     The Client ID for this project (use with IndividualB2C, SingleOrg or MultiOrg auth).
                                  string - Optional
                                  Default: 11111111-1111-1111-11111111111111111

  --domain                        The domain for the directory tenant (use with SingleOrg or IndividualB2C auth).
                                  string - Optional
                                  Default: qualified.domain.name

  --tenant-id                     The TenantId ID of the directory to connect to (use with SingleOrg auth).
                                  string - Optional
                                  Default: 22222222-2222-2222-2222-222222222222

  --callback-path                 The request path within the application's base path of the redirect URI (use with SingleOrg or IndividualB2C auth).
                                  string - Optional
                                  Default: /signin-oidc

  -r|--org-read-access            Whether or not to allow this application read access to the directory (only applies to SingleOrg or MultiOrg auth).
                                  bool - Optional
                                  Default: false / (*) true

  --exclude-launch-settings       Whether to exclude launchSettings.json from the generated template.
                                  bool - Optional
                                  Default: false / (*) true

  --no-https                      Whether to turn off HTTPS. This option only applies if Individual, IndividualB2C, SingleOrg, or MultiOrg aren't used for --auth.
                                  bool - Optional
                                  Default: false / (*) true

  -uld|--use-local-db             Whether to use LocalDB instead of SQLite. This option only applies if --auth Individual or --auth IndividualB2C is specified.
                                  bool - Optional
                                  Default: false / (*) true

  --no-restore                    If specified, skips the automatic restore of the project on create.
                                  bool - Optional
                                  Default: false / (*) true


* Indicates the value used if the switch is provided without a value.

Command Usage – dotnet new mvc:

1. “dotnet new mvc”

The command creates a new “ASP.NET Core MVC Web Application”, the application contains basic boilerplate files and directory. The name of the project is not specified in the command, so by default, the name of the project will be taken from the name of the folder the command has been executed in. The command also restores the dependencies required by the web project. As the default language is C#, a C# ASP.NET MVC project will be created.

The MVC application created is ready to use, on executing the command “dotnet run”, the application will be hosted on local IIS Express server and the same will be listening on the following ports: http://localhost:5000 and https://localhost:5001, details are as follows:

.NET Core MVC application
c:\Temp>dotnet new mvc
The template "ASP.NET Core Web App (Model-View-Controller)" was created successfully.
This template contains technologies from parties other than Microsoft, see https://aka.ms/aspnetcore-template-3pn-210 for details.

Processing post-creation actions...
Running 'dotnet restore' on c:\Temp\Temp.csproj...
  Restore completed in 99.35 ms for c:\Temp\Temp.csproj.

Restore succeeded.

The list of the files and folders created:

c:\Temp>dir
 Volume in drive C is OSDisk
 Volume Serial Number is 8053-FAC8

 Directory of c:\Temp

07/04/2019  07:56 PM    <DIR>          .
07/04/2019  07:56 PM    <DIR>          ..
07/04/2019  07:56 PM               146 appsettings.Development.json
07/04/2019  07:56 PM               192 appsettings.json
07/04/2019  07:56 PM    <DIR>          Controllers
07/04/2019  07:56 PM    <DIR>          Models
07/04/2019  07:56 PM    <DIR>          obj
07/04/2019  07:56 PM               712 Program.cs
07/04/2019  07:56 PM    <DIR>          Properties
07/04/2019  07:56 PM             2,230 Startup.cs
07/04/2019  07:56 PM               183 Temp.csproj
07/04/2019  07:56 PM    <DIR>          Views
07/04/2019  07:56 PM    <DIR>          wwwroot

The content of the Startup.cs file

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace Temp
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
            });


            services.AddControllersWithViews();
            services.AddRazorPages();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseCookiePolicy();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapRazorPages();
            });
        }
    }
}

2. “dotnet new mvc –name MVCWebApplication”

The command creates a directory name MVCWebApplication if already not exists and then creates a new “MVC Web Application” with the name of MVCWebApplication in it, additionally, the command also restores the dependencies required by the project. The list of files and directories created by the command are given below:

c:\>dotnet new mvc --name MVCWebApplication
The template "ASP.NET Core Web App (Model-View-Controller)" was created successfully.
This template contains technologies from parties other than Microsoft, see https://aka.ms/aspnetcore-template-3pn-210 for details.

Processing post-creation actions...
Running 'dotnet restore' on MVCWebApplication\MVCWebApplication.csproj...
  Restore completed in 69.46 ms for c:\MVCWebApplication\MVCWebApplication.csproj.

Restore succeeded.

The list of files and folder created:

c:\MVCWebApplication>dir
 Volume in drive C is OSDisk
 Volume Serial Number is 8053-FAC8

 Directory of c:\MVCWebApplication

07/04/2019  08:01 PM    <DIR>          .
07/04/2019  08:01 PM    <DIR>          ..
07/04/2019  08:01 PM               146 appsettings.Development.json
07/04/2019  08:01 PM               192 appsettings.json
07/04/2019  08:01 PM    <DIR>          Controllers
07/04/2019  08:01 PM    <DIR>          Models
07/04/2019  08:01 PM               183 MVCWebApplication.csproj
07/04/2019  08:01 PM    <DIR>          obj
07/04/2019  08:01 PM               725 Program.cs
07/04/2019  08:01 PM    <DIR>          Properties
07/04/2019  08:01 PM             2,243 Startup.cs
07/04/2019  08:01 PM    <DIR>          Views
07/04/2019  08:01 PM    <DIR>          wwwroot

3. “dotnet new mvc –name FirstWebApplication –no-restore”

The command creates a directory name MVCWebApplication if already not exists and then creates a new “MVC Web Application” in it, additionally, the command does not restore the dependencies required by the project. The list of files and directories created by the command are given below:

c:\>dotnet new mvc --name MVCWebApplication --no-restore
The template "ASP.NET Core Web App (Model-View-Controller)" was created successfully.
This template contains technologies from parties other than Microsoft, see https://aka.ms/aspnetcore-template-3pn-210 for details.

The list of files and folder created

c:\MVCWebApplication>dir
 Volume in drive C is OSDisk
 Volume Serial Number is 8053-FAC8

 Directory of c:\MVCWebApplication

07/04/2019  08:04 PM    <DIR>          .
07/04/2019  08:04 PM    <DIR>          ..
07/04/2019  08:04 PM               146 appsettings.Development.json
07/04/2019  08:04 PM               192 appsettings.json
07/04/2019  08:04 PM    <DIR>          Controllers
07/04/2019  08:04 PM    <DIR>          Models
07/04/2019  08:04 PM               183 MVCWebApplication.csproj
07/04/2019  08:04 PM               725 Program.cs
07/04/2019  08:04 PM    <DIR>          Properties
07/04/2019  08:04 PM             2,243 Startup.cs
07/04/2019  08:04 PM    <DIR>          Views
07/04/2019  08:04 PM    <DIR>          wwwroot

4. “dotnet new mvc –name MVCWebApplication –language F#”

The command creates a directory name FirstWebApplication if already not exists and then creates a new MVC Web Application in it, the programming language for the application is F#, and the extension of the project is .fsproj. Additionally, the command also restores the dependencies required for the project. The list of the files and folder created are given below:

c:\>dotnet new mvc --name MVCWebApplication --language F#
The template "ASP.NET Core Web App (Model-View-Controller)" was created successfully.
This template contains technologies from parties other than Microsoft, see https://aka.ms/aspnetcore-template-3pn-210 for details.

Processing post-creation actions...
Running 'dotnet restore' on MVCWebApplication\MVCWebApplication.fsproj...
  Restore completed in 8.79 sec for c:\MVCWebApplication\MVCWebApplication.fsproj.

Restore succeeded.

The list of files and folders created:

c:\MVCWebApplication>dir
 Volume in drive C is OSDisk
 Volume Serial Number is 8053-FAC8

 Directory of c:\MVCWebApplication

07/04/2019  08:07 PM    <DIR>          .
07/04/2019  08:07 PM    <DIR>          ..
07/04/2019  08:07 PM               146 appsettings.Development.json
07/04/2019  08:07 PM               157 appsettings.json
07/04/2019  08:07 PM    <DIR>          Controllers
07/04/2019  08:07 PM    <DIR>          Models
07/04/2019  08:07 PM               518 MVCWebApplication.fsproj
07/04/2019  08:07 PM    <DIR>          obj
07/04/2019  08:07 PM               674 Program.fs
07/04/2019  08:07 PM    <DIR>          Properties
07/04/2019  08:07 PM             1,905 Startup.fs
07/04/2019  08:07 PM    <DIR>          Views
07/04/2019  08:07 PM    <DIR>          wwwroot

The content of Startup.fs

namespace MVCWebApplication

open System
open System.Collections.Generic
open System.Linq
open System.Threading.Tasks
open Microsoft.AspNetCore.Builder
open Microsoft.AspNetCore.Hosting
open Microsoft.AspNetCore.HttpsPolicy;
open Microsoft.AspNetCore.Mvc
open Microsoft.Extensions.Configuration                                                                                                       open Microsoft.Extensions.DependencyInjection
open Microsoft.Extensions.Hosting

type Startup private () =
    new (configuration: IConfiguration) as this =
        Startup() then
        this.Configuration <- configuration

    // This method gets called by the runtime. Use this method to add services to the container.
    member this.ConfigureServices(services: IServiceCollection) =
        // Add framework services.
        services.AddControllersWithViews().AddRazorRuntimeCompilation() |> ignore
        services.AddRazorPages() |> ignore

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    member this.Configure(app: IApplicationBuilder, env: IWebHostEnvironment) =

        if (env.IsDevelopment()) then
            app.UseDeveloperExceptionPage() |> ignore
        else
            app.UseExceptionHandler("/Home/Error") |> ignore
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts() |> ignore

        app.UseHttpsRedirection() |> ignore
        app.UseStaticFiles() |> ignore

        app.UseRouting() |> ignore

        app.UseAuthorization() |> ignore

        app.UseEndpoints(fun endpoints ->
            endpoints.MapControllerRoute(
                name = "default",
                pattern = "{controller=Home}/{action=Index}/{id?}") |> ignore
            endpoints.MapRazorPages() |> ignore) |> ignore

    member val Configuration : IConfiguration = null with get, set

5. “dotnet new mvc –name MVCWebApplication –no-https”

The command creates a directory name MVCWebApplication only if it does not exists and then creates a new MVC Web Application in it, additionally, the command restores the dependencies required by the project. With –no-https option the command does not assign SSL Port number and neither assigns an https application URL in the launchSettings.json, by default –no-https is false. The content of launchSettings.json with and without –no-https is given below.

a. With –no-https option:

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

b. With default option: –no-https (false)

{
  "iisSettings": {
    "windowsAuthentication": false, 
    "anonymousAuthentication": true, 
    "iisExpress": {
      "applicationUrl": "http://localhost:5253",
      "sslPort": 44300
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "MVCWebApplication": {
      "commandName": "Project",
      "launchBrowser": true,
      "applicationUrl": "https://localhost:5001;http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

Download the latest version of NET Core or refer MSDN for further details

I hope you found this post on how to create an ASP NET Core MVC Web Application using dotnet-cli helpful. Thanks for visiting. Cheers!!!

[Further Readings: How to create an ASP.NET Core Web Application using dotnet-cli |  How to create a dotnet core NUnit Test Project using dotnet-cli |  How to create a dotnet core xUnit Test Project using dotnet-cli |  How to create a dotnet core MSTest Project using dotnet-cli |  How to create dotnet core WinForms Application using dotnet-cli |  How to create a dotnet core WPF application using dotnet-cli |  How to create a dotnet core console app using dotnet-cli |  Top 7 Web Frameworks to Learn and Focus on in 2021   |  Singleton Design Pattern in C#  |  Introduction to Design Patterns  |  How to add Git Bash to Windows Terminal Application  |  How to customize Windows Terminal Application  |  How to customize Windows Terminal Key Bindings    ]

0 0 votes
Article Rating
Subscribe
Notify of
guest
2 Comments
oldest
newest most voted
Inline Feedbacks
View all comments
2
0
Would love your thoughts, please comment.x
()
x