Exploring an ASP.NET Core MVC web application

Let's walk through the parts that make up a modern ASP.NET Core MVC application.

In Visual Studio 2017, look at Solution Explorer for the Ch14_WebApp project. In Visual Studio Code, look at the Explorer pane. Note the following:

  • wwwroot: This folder contains static content, such as CSS for styles, images, JavaScript, and a favicon.ico file.
  • Data: This folder contains Entity Framework Core classes used by the ASP.NET Identity system to provide authentication and authorization.
  • Dependencies (Visual Studio 2017 only): This folder contains a graphical representation of Bower and NuGet for modern package management. The actual files are bower.json and Ch14_WebApp.csproj. In Visual Studio 2017, you could edit the project manually by right-clicking the project and choosing Edit Ch14_WebApp.csproj.
  • Ch14_WebApp.csproj: This file contains a list of NuGet packages, such as the Entity Framework Core, that your project requires.
  • .vscode/launch.json (Visual Studio Code only) and Properties/launchSettings.json (Visual Studio 2017 only): These files configure options for starting the web application from inside your development environment.
  • Controllers: This folder contains C# classes that have methods (known as actions) that fetch a model and pass it to a view.
  • Models: This folder contains C# classes that represent all the data required to respond to an HTTP request.
  • Views: This folder contains .cshtml files that combine HTML and C# code to enable the dynamic generation of an HTML response.
  • Services: This folder contains C# interfaces and classes for integrating with external services, such as SMS for sending text messages.
  • appsettings.json: This file contains settings that your web application can load at runtime, for example, the database connection string for the ASP.NET Identity system.
  • bower.json: This file contains client-side packages that combine resources such as jQuery and Bootstrap.
  • gulpfile.js: This file is an optional task runner that can perform actions such as bundling and minimization.
  • Program.cs: This file is a console application that contains the Main entry point that performs initial configuration, compilation, and executes the web application. It can call the UseStartup<T>() method to specify another class that can perform additional configuration.
  • Startup.cs: This optional file performs additional configuration of the services, for example, ASP.NET Identity for authentication, SQLite for data storage, and so on, and routes for your application.

ASP.NET Core startup

Open the Startup.cs file.

Note the ConfigureServices method that adds support for MVC along with other framework and application services such as ASP.NET Identity, as shown in the following code:

    public void ConfigureServices(IServiceCollection services) 
    { 
      // Add framework services. 
      services.AddDbContext<ApplicationDbContext>(options => 
        options.UseSqlServer(Configuration 
        .GetConnectionString("DefaultConnection"))); 
   
      services.AddIdentity<ApplicationUser, IdentityRole>() 
        .AddEntityFrameworkStores<ApplicationDbContext>() 
        .AddDefaultTokenProviders(); 
 
      services.AddMvc(); 
 
      // Add application services. 
      services.AddTransient<IEmailSender, AuthMessageSender>(); 
      services.AddTransient<ISmsSender, AuthMessageSender>(); 
    } 

Next, we have the Configure method. Note the following:

  • If the web application is running in the development environment, then (1) when an exception is thrown, a rich error page showing source code is displayed, and (2) browser link is enabled so that Visual Studio tools can push updates to the actively running browsers.
  • Static files are enabled to allow CSS, JavaScript, and so on, to be served from the file system.
  • ASP.NET Identity is enabled for authentication and authorization.
  • The most important statement here is the one that calls UseMvc and maps a default route. This route is very flexible, because it would map to almost any incoming URL, as you will see in the next section:
    public void Configure(IApplicationBuilder app,  
      IHostingEnvironment env, ILoggerFactory loggerFactory) 
    { 
      loggerFactory.AddConsole(Configuration.GetSection("Logging")); 
      loggerFactory.AddDebug(); 
 
      if (env.IsDevelopment()) 
      { 
        app.UseDeveloperExceptionPage(); 
        app.UseDatabaseErrorPage(); 
        app.UseBrowserLink(); 
      } 
      else 
      { 
        app.UseExceptionHandler("/Home/Error"); 
      } 
 
      app.UseStaticFiles(); 
 
      app.UseIdentity(); 
 
      app.UseMvc(routes => 
      { 
        routes.MapRoute( 
          name: "default", 
          template: "{controller=Home}/{action=Index}/{id?}"); 
      }); 
    } 

Understanding the default route

The default route looks at any URL entered by the user in the address bar and matches it to extract the name of a controller, the name of an action, and an optional id value (the ? symbol makes it optional). If the user hasn't entered these names, it uses defaults of Home for the controller and Index for the action (the = assignment sets a default for a named segment).

Contents in curly-brackets {} are called segments, and they are like a named parameter of a method. The value of these segments can be any string.

The responsibility of a route is to discover the name of a controller and an action.

The following table contains example URLs and how MVC would work out the names:

URL

Controller

Action

ID

/

Home

Index

/Muppet

Muppet

Index

/Muppet/Kermit

Muppet

Kermit

/Muppet/Kermit/Green

Muppet

Kermit

Green

/Products

Products

Index

/Products/Detail

Products

Detail

/Products/Detail/3

Products

Detail

3

Note that if the user does not supply a name, then the defaults, Home and Index, are used as specified when the route was registered. You could change these defaults if you wanted.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.254.61