Header add


In this article we will discuss about ASP .NET Core MVC Web application Project Structure.
If you are new to .NET Core MVC it is necessary to learn what are the folder structure and how they works. We gonna discuss about the MVC Structure first.

What is the MVC pattern?

The Model-View-Controller (MVC) architectural pattern separates an application into three main groups of components: Models, Views, and Controllers. 

Model: With help model class we create our business logic.
Views:  Views are used for presenting the UI of project with interaction of controllers.
Controllers: Controllers are the components that handle user interaction, work with the model, and ultimately select a view to render. Controller is the heart of MVC pattern and is responsible for selecting which model types to work with and which view to render.

Project Structure of .NET Core
Now we Create the ASP .NET Core Project and discuss about the folder Structure.
We are using C# as the programming language, so the project file has .csproj extension. If you use Visual Basic as the programming language, then the project file extension is .vbproj.
1) .csproj extension : Right click on solution folder and edit the .csproj file. 
     <Project Sdk="Microsoft.NET.Sdk.Web">  
      <PropertyGroup>  
       <TargetFramework>netcoreapp2.2</TargetFramework>  
       <AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>  
      </PropertyGroup>  
      <ItemGroup>  
       <PackageReference Include="Microsoft.AspNetCore.App" />  
       <PackageReference Include="Microsoft.AspNetCore.Razor.Design" 
              Version="2.2.0" PrivateAssets="All" />  
      </ItemGroup>  
     </Project>  
TargetFramework : As the name implies this element is used to specify the target framework for your application i.e the set of APIs that you'd like to make available to the application. Our application targets netcoreapp2.2. When we created this application, we selected .NET Core 2.2 as the target framework from the New Project Dialog drop-down list.
AspNetCoreHostingModel : This element specifies how the asp.net core application should be hosted. Should it be hosted InProcess or OutOfProcess. The value of InProcess specifies that we want to use in-process hosting model i.e host our asp.net core app inside of the IIS worker process (w3wp.exe). The value of OutOfProcess specifies that we want to use  out-of-process hosting model i.e forward web requests to a back-end ASP.NET Core app running the Kestrel server. We will discuss InProcess and OutOfProcess hosting in detail in our upcoming videos.
PackageReference : As the name implies, this element is used to include a reference to all the NuGet packages that are installed for your application. At the moment in the project file we have the following 2 NuGet packages.
Microsoft.AspNetCore.App
Microsoft.AspNetCore.Razor.Design
Microsoft.AspNetCore.App : This NuGet package is called metapackage. A metapackage has no content of its own but is a list of dependencies (other packages). You can find this metapackage, in the Solution Explorer, under NuGet which in turn is under Dependencies. When you expand the metapackage, you can find all the dependencies.
2) launchSettings.json: It describes how a project can be launched and describes the command to run, whether the browser should be opened, which environment variables etc.
    {  
      "iisSettings": {  
       "windowsAuthentication": false,   
       "anonymousAuthentication": true,   
       "iisExpress": {  
        "applicationUrl": "http://localhost:61265",  
        "sslPort": 0  
       }  
      },  
      "profiles": {  
       "IIS Express": {  
        "commandName": "IISExpress",  
        "launchBrowser": true,  
        "environmentVariables": {  
         "ASPNETCORE_ENVIRONMENT": "Development"  
        }  
       },  
       "COREMVC_ProjectStructure": {  
        "commandName": "Project",  
        "launchBrowser": true,  
        "applicationUrl": "http://localhost:5000",  
        "environmentVariables": {  
         "ASPNETCORE_ENVIRONMENT": "Development"  
        }  
       }  
      }  
     }  
This file is find on "Properties" folder in the project root folder.This file is only used on local development machine.We usually store our application configuration settings in this file.We can also have environment specific appsettings.json files. For example, appsettings.Staging.json for the staging environment. In ASP.NET Core, in addition to appsettings.json file, we also have other configuration sources like Environment variables, User Secrets, Command Line Arguments and even our own custom configuration source.
3) appSettings.json: It is used to store information of connection strings and application specific settings.These are stored in the JSON format as the file extension suggests. You can see we added a key name "Corekey" in the appsettings.json. We will show how to access the key value in startup.cs file in below section.
    {  
      "Logging": {  
       "LogLevel": {  
        "Default": "Warning"  
       }  
      },  
      "AllowedHosts": "*",  
      "CoreKey": "CoreKey value get from appsettings.json"  
     }  
4) wwwroot: These folder contains all the static files such as css,js,images etc.
5) Program.cs: It is the main entry point for the application like console application in .NET framework. It then goes to the Startup.cs class to finalize the configuration of the application.
    public class Program  
       {  
         public static void Main(string[] args)  
         {  
           CreateWebHostBuilder(args).Build().Run();  
         }  
         public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>  
           WebHost.CreateDefaultBuilder(args)  
             .UseStartup<Startup>();  
       }  
if you take a look at the Main() method, it calls CreateWebHostBuilder() method passing it the command line arguments.
  1. CreateWebHostBuilder() method returns an object that implements IWebHostBuilder.
  2. Build() method is called which builds a web host that hosts our asp.net core web application.
  3. Run() method is called, which runs the web application and it begins listening for incoming HTTP requests.
CreateWebHostBuilder() method calls CreateDefaultBuilder() method of the WebHost class.
6) Startup.cs: It includes Configure and ConfigureServices methods. And routing concept is introduce here. The Dependency Injection pattern is used heavily in ASP.NET Core architecture. It includes built-in IoC container to provide dependent objects using constructors.
ConfigureServices method is a place where you can register your dependent classes with the built-in IoC container (ASP.NET Core refers dependent class as a Service). After registering the dependent class, it can be used anywhere in the application. You just need to include it in the parameter of the constructor of a class where you want to use it. The IoC container will inject it automatically.
Configuremethod is used to specify how the app responds to HTTP requests. The request pipeline is configured by adding middleware components to an IApplicationBuilder instance. IApplicationBuilder is available to the Configure method, but it isn’t registered in the service container. Hosting creates an IApplicationBuilder and passes it directly to the Configure method.
    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;  
             options.MinimumSameSitePolicy = SameSiteMode.None;  
           });  
           services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);  
         }  
         // This method gets called by the runtime. Use this 
         //method to configure the HTTP request pipeline.  
         public void Configure(IApplicationBuilder app, IHostingEnvironment env)  
         {  
           if (env.IsDevelopment())  
           {  
             app.UseDeveloperExceptionPage();  
           }  
           else  
           {  
             app.UseExceptionHandler("/Home/Error");  
           }  
           app.UseStaticFiles();  
           app.UseCookiePolicy();  
           app.UseMvc(routes =>  
           {  
             routes.MapRoute(  
               name: "default",  
               template: "{controller=Home}/{action=Index}/{id?}");  
           });  
         }  
       }  
The route Config is set in startup.cs under Configure method file that make the navigation 
     app.UseMvc(routes =>
                {
                    routes.MapRoute(
                        name: "default",
                        template: "{controller=Home}/{action=Index}/{id?}");
                });
You can see the Controller is set ad "Home" and action is set as "Index". You can set your own controller and action method accordingly.
Accessing configuration information
To access configuration information in the Startup class, inject the IConfiguration service provided by the Framework. Startup class is in Startup.cs file.
    public class Startup  
     {  
       private IConfiguration _configuration;  
       // Notice we are using Dependency Injection here  
       public Startup(IConfiguration configuration)  
       {  
         _configuration = configuration;  
       }  
       public void ConfigureServices(IServiceCollection services)  
       {  
       }  
       public void Configure(IApplicationBuilder app, IHostingEnvironment env)  
       {  
         if (env.IsDevelopment())  
         {  
           app.UseDeveloperExceptionPage();  
         }  
         app.Run(async (context) =>  
         {  
           await context.Response.WriteAsync(_configuration["CoreKey"]);  
         });  
       }  
     }  
You can see we already declare the Key value in appsettings.json file, to access the key value we follow the above way.

Finally we can see in below diagram the .NET Core application Flow.



Summary
In this tutorial we discussed about the .NET Core MVC Process flow and Folder Structure. If  have any question related to this topic you can give your feedback.

Post a Comment

Previous Post Next Post