You can see the FirstAppDemo project and the web application. Now double click on the folder.

 ASP.NET Core - Quick Guide

These are the pennies rce the code files for the application and you can also see this folder structure in the Solution Explorer window, because in the current version of ASP.NET Core the file system determines the contents of your project.

If you adda new file on disk, the file will be added to the project. If you delete a file, the file is deleted from the project. Everything stays in sync and it's a little different from previous versions of ASP.NET Core where a project file, a proj * .cs file, which contained a manifest of everything in the project.

ASP.NET Core also compiles your app when a file changes or a new file appears.

Example

Let's see a simple example by opening the Startup.cs in the text editor.

 ASP.NET Core - Quick Guide

It 's this line code that responds to every HTTP request to your application and it simply responds with Hello World!

Let's change the string in the screenshot above to say " Hello everyone! This ASP.NET Core application ”as shown in the following program.

using System; using System.Collections.Generic; using System.Linq; using System .Threading.Tasks; in Cusing Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; namespace FirstAppDemo {public class Startup {// This method is called by the runtime. // Use this method to add services to the container. // For more information on configuring your application, // visit http: //go.microsoft.com/fw/? LinkID "= 398940 " "" "" "" public void ConfigureServices (IServiceCollection services) {} // This method is called by the runtime. // Use this method to configure the HTTP request pipeline. public void Configure (IApplicationBuilder application, IHostingEnvironment env, ILoggerFactory loggerFactory) {loggerFactory.AddConsole if (env.IsDevelopment ()) {app.UseDeveloperExceptionPage } app.Run ((context) => {await context.Response.WriteAsync ( "Hello World! This ASP.NET Core Application ");});}}}

Save this file in the text editor by pressing Ctrl + S, then return to the web browser and refresh the application.

 ASP.NET Core - Quick Guide

You can now see that your changes are reflected in the browser.

ASP.NET Core - Project.Json

In this chapter we have the project.json file. This file uses JavaScript object notation to store configuration information, and it is this file that is really the heart of a .NET application. Without this file, you would not have an ASP.NET Core project. Here we are going to discuss some of the most important features of this file. Double-click on the project.json file.

 ASP.NET Core - Quick Guide

Currently the default code implementation in the project.json file is as follows -

{ "dependencies ": { "Microsoft.NETCore.App ": { "version ": "1.0.0 ", "type ": " platform "}, " Microsoft.AspNetCore.Diagnostics ": " 1.0.0 ", " Microsoft.AspNetCore.Server.IISIntegration ": " 1.0. 0 ", " Microsoft.AspNetCore.Server.Kestrel ": " 1.0.0 ", " Microsoft.Extensions.Logging.Console ": " 1.0.0 "}, " tools ": {" 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 ", " web.config "]}, " s ": {" postpublish ": [" dotnet publish-iis --publish-folder% publish: OutputPath% --framework% publish: FullTargetFramework% "]}}

As we see, we have version information at the top of this file. This is the version number that your app will use when you build it.

"Microsoft.AspNetCore.Diagnostics ": "1.0.0 ", "Microsoft.AspNetCore.Server.IISIntegration ": " 1.0.0 ", " Microsoft.AspNetCore.Server.Kestrel ": " 1.0.0 ", " Microsoft.Extensions.Logging.Console ": " 1.0.0

You can see that we have somedependencies in this file and the exact dependencies will likely be changed by the final version of ASP.NET. When you want to add a new dependency, for example like ASP.NET MVC framework, you easily type in this project.json file, and you will also get IntelliSense help, including not just the name of the package, but also the version numbers as shown in the following screenshot.

ASP.NET Core - Quick Guide

You can also use the UI by right-clicking References in Solution Explorer and then selecting Manage NuGet Packages . You can now see the currently installed packages.

 ASP.NET Core - Quick Guide

These packages are the same as those in your project.json file and you can also go to the browser and add other packages including pre-released packages, say, the MVC framework installed in this project.

 ASP .NET Core Quick Guide

If you install this package now using the Install button,then this package will be stored in project.json. Another important part of project.json is the frameworks section, this section tells ASP.NET which of the .NET frameworks your application can use.

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

In this case you will see that " netcoreapp1.0 "is the framework used in the project, you can also include the The full .NET Framework that is installed when you install Visual Studio.

ASP.NET Core - Configuration

In this chapter, we will discuss the configuration related to the ASP.NET Core project. In Solution Explorer, you will see the Startup.cs file. If you've worked with previous versions of ASP.NET Core, you'd probably expect to see a global.asax file, which was a place you could write code to run when starting a web application.

  • You would also expect to see a web.config file containing all the configuration parameters that your application avait needs to run.

  • In ASP.NET Core these files are all gone, and instead of configuration and startup code, they are loaded from Startup.cs.

  • There is a startup class in the file and in this class you can configure your application and even configure your configuration sources.

  • This is the default implementation in 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.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; namespace FirstAppDemo {public class Startup {// This method is called by the runtime. // Use this method to add services to the container. // For more informationinstructions on configuring your application, // visit http: //go.microsoft.com/fw/? LinkID "= 398940 " "" "" "" public void ConfigureServices (IServiceCollection services) {} // This method is called by the runtime. Use this method to configure // the HTTP request pipeline. public void Configure (IApplicationBuilder application, IHostingEnvironment env, ILoggerFactory loggerFactory) {loggerFactory.AddConsole if (env.IsDevelopment ()) {app.UseDeveloperExceptionPage } app.Run ((context) => {await context.Response.WriteAsync ( "Hello World! ");}); }}}

    In the Startup class, there are two methods where most of our work will take place. The Configure method of the class is where you build your HTTP processing pipeline.

    Right now we have a hard-coded string for each response - the Hello World ! chain. Instead of hard-coding the string, we want to load this string from a component that knows the text we want to display.

    In Solution Explorer, right click on your project node and select Add → New Item .

     ASP.NET Core - Quick Guide

    In the left pane, select Installed → Code then in the middle pane, select the JSON file. Call this file AppSettings.json and click on the Add button as in the above.

     ASP.NET Core - Quick Guide

    We can also tell our program to read the text from the file instead of having the Hello World! string in Startup.cs. following code in AppSettings.json .

    { "message ": "Hello, World! this message comes from the configuration file ... "}

    We now need to access this message fromthen the Startup.cs file. Here is the implementation of the Startup.cs file which will read the above message from the JSON file.

    using Microsoft.AspNet.Builder; using Microsoft.AspNet.Hosting; using Microsoft.AspNet.Http; using Microsoft. Extensions.DependencyInjection; using Microsoft.Extensions.Configuration; namespace FirstAppDemo {public class Startup {public Startup () {var builder = new ConfigurationBuilder () .AddJsonFile ( "AppSettings.json "); Configuration = builder.Build } public IConfiguration Configuration {get; set;} // This method is called by the runtime. // Use this method to add services to the container. // For more information on configuring your application, // visit http: / /go.microsoft.com/fw/?LinkID=398940 public void ConfigureServices (IServiceCollection services) {} // This method is called by the execution engine. // Utiread this method to configure the HTTP request pipeline. public void Configure (IApplicationBuilder application) {app.UseIISPlatformHandler app.Run ((context) => {var msg = Configuration [ "message "]; wait for context.Response.WriteAsync (msg);}); } // Entry point of the application. public static void Ma in (string args) = 7gt; WebApplication.Run (args); }}

    Now let's launch the application. Once the application is executed, it will produce the following output.

     ASP.NET Core - Quick Guide

    ASP.NET Core - Middleware

    In this chapter, we will understand how to put set up middleware. Middleware in ASP.NET Core controls how our application responds to HTTP requests. It can also control how our application looks in the event of an error, and this is a key in how we authenticate and authorize a user to perform specific actions.

    Now suppose we want to log information about every query in our application.

     ASP.NET Core - Quick Guide

    Example

    Now let's take a simple example to learn more about middleware. We configured the middleware in ASP.NET using the Configure method of our startup class .

    using Microsoft.AspNet.Builder; using Microsoft.AspNet.Hosting; using Microsoft.AspNet.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Configuration; namespace FirstAppDemo {public class Startup {public Startup () {var builder = new ConfigurationBuilder () .AddJsonFile ( "AppSettings.json "); Configuration = constructor.Build } Public IConfiguration configuration {get; together; } // This method ist called by the runtime. // Use this method to add services to the container. // For more information on configuring your application, // visit http: //go.microsoft.com/fw/? LinkID "= 398940 " "" "" "" public void ConfigureServices (IServiceCollection services) {} // This method is called by the runtime. // Use this method to configure the HTTP request pipeline. public void Configure (IApplicationBuilder application) {app.UseIISPlatformHandler app.Run ((co ntext) => {var msg = Configuration [ "message "]; wait for context.Response.WriteAsync (msg);}); } // Entry point of the application. public static void Main (string args) => WebApplication.Run (args); }}

    In the Configure () method, we will invoke extension methods on the IApplicationBuilder interface to add middleware.

    There are two middleware items in a new empty project by default -

    IISPlatformHandler

    IISPlatformHandler allows us to work with the Windows authentication. It will examine each incoming request and see if there is any Windows identity information associated with that request, then it calls the next middleware.

    Middleware registered with app.Run

    The next middleware in this case is middleware registered with app.Run . The Run method allows us to pass another method, which we can use to process each response. Run is not something you will see very often, it is something that we call terminal middleware.

    The middleware that you register with Run will never get a chance to call other middleware, all that does is receive a request and then it should produce some sort of response.

    You also have access to a Response object and one of the thingsThe thing you can do with a Response object is write a string.

    If you want to register another middleware after app.Run, that middleware will never be called because, again, Run is terminal middleware. It will never call the next middleware.

    How to add another middleware

    Let's continue with the following steps to add another middleware -

    Step 1 - To add a other middleware, right-click on the project and select Manage NuGet Packages.

    Step 2 - Find Microsoft.aspnet .diagnostics This is actually ASP.NET Core middleware for handling exceptions, pages Exception display and diagnostic information. This particular package contains many middleware components that we can use.

     ASP.NET Core - Quick Guide

    Step 3 - Install this package if it is not installed in your project.

    Step 4 - Now let's move onto the Configure () method and invoke the app.UseWelcomePage middleware.

    // This method is called by the runtime. // Use this method to configure the HTTP request pipeline. public void Configure (IApplicationBuilder application) {app.UseIISPlatformHandler app.UseWelcomePage app.Run ((context) => {var msg = Configuration [ "message "]; wait for context.Response.WriteAsync (msg);}); }

    Step 5 - Launch your application and you will see the following welcome screen.

     ASP.NET Core - Quick Guide

    This welcome screen may not be as useful.

    Step 6 - Let's try something else that might be a little more useful. Instead of using the home page, we'll be using the RuntimeInfoPage .

    // This method is called by the runtime. // Use this method to configure the HTTP request pipeline. public void Configure (IAp applicationplicationBuilder) {app.UseIISPlatformHandler app.UseRuntimeInfoPage app.Run ((context) => {var msg = Configuration [ "message "]; wait for context.Response.WriteAsync (msg);}); }

    Step 7 - Save your Startup.cs page and refresh your browser and you will see the following page.

     ASP.NET Core - Quick guide

    This RuntimeInfoPage is a middleware that will only respond to requests from a specific URL. If the incoming request does not match that URL, this middleware just leaves the request move on to the next middleware. The request will go through the IISPlatformHandler middleware, then go to the UseRuntimeInfoPage middleware. It will not create a response, so it will go into our application. Run and display the string.

    Step 8 - Let's add "/ runtimeinfo " to the end of your URL. You will now see a page produced by this runtime info page middleware.

    ASP.NET Core Quick Guide

    You will now see a response that gives you informationons on your runtime environment such as operating system, runtime version, architecture, type and any packages you are using etc.

    ASP.NET Core - Exceptions

    In this chapter, we will discuss exceptions and error handling . When errors occur in your ASP.NET Core application, there are a number of ways you can handle them. Let's see another middleware available through the diagnostic package. This middleware will help us deal with errors.

    To fake an error, let's go to app.Run and see how the application behaves if we throw an exception every time we hit this piece of middleware.

    using Microsoft.AspNet.Builder; using Microsoft.AspNet.Hosting; using Microsoft.AspNet.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Configuration; namespace FirstAppDemo {public class Startup {public Startup () {var builder = new ConfigurationBuilder () .AddJsonFile ( "AppSettings.json "); Configuration = constructor.Build } Public IConfiguration configuration {get; together; } // This method is called by the runtime. // Use this method to add services to the container. // For more information on configuring your application, // visit http: //go.microsoft.com/fw/? LinkID "= 398940 " "" "" " "public void ConfigureServices (IServiceCollection services) {} // This method is called by the runtime. // Use this method to configure the HTTP request pipeline. public void Configure (IApplicationBuilder application) {app.UseIISPlatformHandler app.UseRuntimeInfoPage app.Run ((context) => {throw new System.Exception ( "Throw Exception "); var msg = Configuration [ "message "]; wait context.Response.WriteAsync (msg);}); } // Entry point of the application. public static void Main (string args) => WebApplication.Run (args); }}

    It will just throw an exception with a very generic message. Save the Startup.cs page and run your application.

    ASP.NET Core - Quick Guide

    You will see that we have failed to load this resource. There was an HTTP 500 error, an internal server error, and this is not very helpful. It may be useful to get information about exceptions.

    Let's add another middleware, which is the UseDeveloperExceptionPage .

    // This method is called by the runtime. // Use this method to configure the HTTP request pipeline. public void Configure (IApplicationBuilder application) {app.UseIISPlatformHandler app.UseDeveloperExceptionPage app.UseRuntimeInfoPage app.Run ((context) => {throw new System.Exception ( "Throw Exception "); var msg = Configuration [ "message "]; wait context.Response.WriteAsync (msg);}); }

    Let's run the application again. It will produce output as shown in the following screenshot.

     ASP .NET Core Quick Guide

    You will now see information that you would expect if there was a development error. You will also get a stack trace and you will see that an unhandled exception has been throwne on line 37 of Startup.cs.

    You can also see the raw details of exceptions and all of this information can be very useful for a developer. In fact, we probably only want to display this information when a developer is running the app.

    ASP.NET Core - Static files

    In this chapter we will learn how to work with files. An important feature that almost all web applications need is the ability to serve files (static files) from the file system.

    Example

    Now let's take a simple example in which we will understand how we can serve these files in our application.

    Here we want to add a simple HTML file to our FirstAppDemo application and this HTML file should go to the web root folder (wwwroot). Right click on the wwwroot folder in Solution Explorer and select Add → New Item .

     ASP.NET Core - Quick Guide

    In the middle pane, select the HTML Page and name it index.html and click on the Add button.

     ASP.NET Core Quick Guide

    You will see a simple index.html file. Let's add some simple text and title as shown below.

    < charset="utf-8" /> Welcome to ASP. NET Core Hello, Wolrd! This message is from our first static HTML file.

    When you run your appcation and navigate to index.html in the browser, you will see that the app.Run middleware throws an exception because there is nothing currently in our application.

     ASP.NET Core - Quick Guidee

    There is no middleware that will go looking for a file on the filesystem to serve. To resolve this problem, navigate to to NuGet Package Manager by right-clicking your project in Solution Explorer and selecting Manage NuGet Packages.

     ASP.NET Core - Quick Guide

    Find Microsoft.AspNet.StaticFiles which will find the middleware for the static files. this nuget package and now we should have some additional methods that we can use to register the middleware in the Configure method.

    Let's add UseStaticFiles middle in the Configure method as shown in the program next.

    using Microsoft.AspNet.Builder; using Microsoft.AspNet.Hosting; using utireading Microsoft.AspNet.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Configuration; namespace FirstAppDemo {public class Startup {public Startup () {var builder = new ConfigurationBuilder () .AddJsonFile ( "AppSettings.json "); Configuration = constructor.Build } Public IConfiguration configuration {get; together; } // This method is called by the runtime. // Use this method to add services to the container. // For more information on configuring your application, // visit http: //go.microsoft.com/fw/? LinkID "= 398940 " "" "" "" public void ConfigureServices (IServiceCollection services) {} // This method is called by the runtime. // Use this method to configure the HTTP request pipeline. public void Configure (IApplicationBuilder application) {app.UseIISPlatformHandler app.UseDeveloperExceptionPage app.UseRuntimeInfoPage app.UseStaticFiles app.Run ((context) =>{throw new System.Exception ( "Throw Exception "); var msg = Configuration [ "message "]; wait context.Response.WriteAsync (msg);}); } // Entry point of the application. public static void Main (string args) => WebApplication.Run (args); }}

    Unless you override the options and pass some different configuration parameters, static files will make for a given query look at query path . This query path is then compared against the file system and what is on the file system.

    Let's save the Startup.cs file and refresh your browser.

     ASP.NET Core - Quick Guide

    You can nownant see the index.html file. Anything you put anywhere in the wwwroot - any JavaScript or CSS or HTML file, you can serve them.

    // This method is called by the runtime. // Use this method to configurethe HTTP request pipeline. public void Configure (IApplicationBuilder application) {app.UseIISPlatformHandler app.UseDeveloperExceptionPage app.UseRuntimeInfoPage app.UseDefaultFiles app.UseStaticFiles app.Run ((context) => {var msg = Configuration [ "message "]; wait for context.Response.WriteAsync (msg);}); }

    Let's save the Startup.cs file and go to the root of the web application in your browser.

     ASP.NET Core - Quick Guide

    You can now see that index.html is your default file. The order in which you install the middleware is important because if vIf you had UseDefaultFiles after UseStaticFiles, you wouldn't get the same result.

    If you are going to be using UseDefaultFiles and UseStaticFiles, you might also want another piece of middleware that is in the Microsoft.aspnet.staticfiles package, NuGet, and that is the FileServer middleware . This basically includes the Default Files and the Static Files in the correct order.

    // This method is called by the runtime. // Use this method to configure the HTTP request pipeline. public void Configure (IApplicationBuilder application) {app.UseIISPlatformHandler app.UseDeveloperExceptionPage app.UseRuntimeInfoPage app. UseFileServer app.Run ((context) => {var msg = Configuration [ "message "]; wait for context.Response.WriteAsync (msg);}); }

    Let's back up the Startup.cs file again. Once you refresh the browser you will see the same result.as shown in the following screenshot.

     ASP.NET Core - Quick Guide

    ASP.NET Core - Setup MVC

    In this chapter, we will configure the MVC framework in our FirstAppDemo application. do this by building a web app on top of ASP.NET Core, and more specifically, the ASP.NET Core MVC framework. We can technically build an entire app using just middleware, but ASP.NET Core MVC gives us the functionality that we can use to easily create HTML pages and HTTP based APIs.

    To configure MVC framework in our empty project, follow these steps -

    Step 1 - Either Access the NuGet Package Manager by right-clicking on Manage NuGet Packages. Install the Microsoft.AspNet.Mvc package, which gives us access to the assemblies and classes provided by the framework.

     ASP.NET Core - Quick Guide

    Step 2 - Once the Microsoft.AspNet.Mvc package is installed, we need to register all the services required by ASP.NET Core MVC at runtime. We will do this with the ConfigureServices method. We will also add a simple controller and see output from that controller.

    Let's add a new folder to this project and call it Controllers . In this folder we can place multiple controllers as shown belowou in Solution Explorer.

     ASP.NET Core - Quick Guide

    Now right click on the Controllers folder and select the menu option Add → Class .

     ASP.NET Core - Quick Guide

    Step 3 - Here we want to add a simple C # class, and call this HomeController class, then click on the Add button as in the screenshot above.

     ASP.NET Core Quick Guide

    This will be our default page.

    Step 4 - Let's define just one public method that returns a string and let's call that Index method as shown in the following program.

    using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace FirstAppdemo.Controllers {public class HomeController {public string Index () {return "Hello, World! this message is from Home Controller ...}}}

    Step 5 - When you go to the root of the website, you want to see the response from the controller. From now on wewill serve our index.html file.

     ASP.NET Core - Quick Guide

    Let's go to the root of the website and delete index.html. We want the controller to respond instead of the index.html file.

    Step 6 - Now go to the Configure method in the Startup class and add the UseMvcWithDefaultRoute middleware piece.

     ASP.NET Core - Quick Guide

    Step 7 - Now refresh the application at the root of the website.

     ASP.NET Core - Quick Guide

    You will encounter a 500 error. 'error indicates that the framework could not find the required ASP.NET Core MVC services.

    The ASP.NET Core Framework itself is made up of different small components that have very focused responsibilities.

    For example, there is a component that needs to locate and instantiate the controller.

    This component must be in the service collection for ASP.NET Core MVC to work properly.

    Step 8 - Besides adding the NuGet package and middleware, we also need to add the AddMvc service ins the ConfigureServices. Here is the full implementation of the Startup class.

    using Microsoft.AspNet.Builder; using Microsoft.AspNet.Hosting; using Microsoft.AspNet.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Configuration; namespace FirstAppDemo {public class Startup {public Startup () {var builder = new ConfigurationBuilder () .AddJsonFile ( "AppSettings.json "); Configuration = constructor.Build } Public IConfiguration configuration {get; together; } // This method is called by the runtime. // Use this method to add services to the container. // For more information on configuring your application, // visit http: //go.microsoft.com/fw/? LinkID "= 398940 " "" "" " "public void ConfigureServices (IServiceCollection services) {services.AddMvc } // This method is called by the runtime. // Use this method to configurethe HTTP request pipeline. public void Configure (IApplicationBuilder application) {app.UseIISPlatformHandler app.UseDeveloperExceptionPage app.UseRuntimeInfoPage app.UseFileServer app.UseMvcWithDefaultRoute app.Run ((context) => {var msg = Configuration [ "message "]; wait for context.Response.WriteAsync (msg);}); } // Entry point of the application. public static void Main (string args) => WebApplication.Run (args); }}

    Step 9 - Save the Startup.cs file and go to the browser and refresh it. You will now receive a response from our home controller .

     ASP.NET Core - Quick Guide

    ASP.NET Core - MVC Design Template

    The Model-View-Controller (MVC) design pattern is a design pattern that has actually been around for a few decades, and it has been used in many different technologies, from Smalltalk to C ++ to Java and now in C # and .NET as a design template to uUse this when you 're building a user interface.

    The MVC separates the user interface (UI) from an application into the following three parts -

    Idea behind MVC

    Now let's understand the idea behind MVC.

     ASP.NET Core - Quick guide

    In MVC, the controller receives a request HTTP, the controller needs to figure out how to gather the information to answer this request. Maybe the user is directing the browser to the application url / books. So the controller needs to gather the information to display a list of books. In this scenario, the controller will build a model.

     ASP.NET Core - Quick Guide

    These are the basics of the MVC design pattern and the idea behind this pattern is to keep a separation of concerns. Thus, the controller is only responsible for taking a request and creating a model. It is the model that carries the logic and data that we need into the view. Then the view is only responsible for transforming that model into HTML.

    ASP.NET Core - Routing

    In the MVC framework, we have three components, each with its own focus on one that's part of the job. For all of this to work, we need to find a way to send these HTTP requests to the right controller. In ASP.NET Core MVC, this process is called routing. Routing is the process of directing an HTTP request to a controller.

    Now let's see how to route requests to different controllers.

    routeBuilder.MapRoute ( "Default ", "{controller = Home} / {action = Index} / {id ?} ");

    In the last chapter, we created a controller (HomeController) in our application which is a C # class and which does not does not need to be derived from a base class or implement an interface or have a special attribute. It's a simple C # class with a name, HomeController, and it contains the Index method which returns a string.

    using System; using System.Collections.Generic; use of System.Linq; use of System.Threading.Tasks; namespace FirstAppdemo.Controllers {public class HomeController {public string Index () {return "Hello, World! this message is from Home Controller ...}}}

    Here we will focus on routing to controllers . We will also try to understand how routing works.

    Now back to the Startup class where we configured the middleware MVC in our application. In the Configure method, we used a UseMvcWithDefaultRoute method.

    public void Configure (application IApplicationBuilder) {app.UseIISPlatformHandler app.UseDeveloperExceptionPage app.UseRuntimeInfoPage app.UseFileServer app.UseMvRoute app.Run ((context) => {var msg = Configuration [ "message "]; wait context.Response.WriteAsync (msg);});}

    This gives us adefault routing rule that allows us to access the HomeController . Instead of using UseMvcWithDefaultRoute , let's use the UseMvc , then configure the route at this point using a method named ConfigureRoute . The following is the implementation of the Startup.cs file.

    using Microsof t.AspNet.Builder; using Microsoft.AspNet.Hosting; using Microsoft.AspNet.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Configuration; using Microsoft.AspNet.Routing; using the system; namespace FirstAppDemo {public class Startup {public Startup () {var builder = new ConfigurationBuilder () .AddJsonFile ( "AppSettings.json "); Configuration = constructor.Build } Public IConfiguration configuration {get; together; } // This method is called by the runtime. // Use this method to add services to the container. // Formore information about configuring your application, // visit http: //go.microsoft.com/fw/? LinkID "= 398940 " "" "" "" public void ConfigureServices (IServiceCollection services) {services.AddMvc } // This method is called by the runtime. // Use this method to configure the HTTP request pipeline. public void Configure (IApplicationBuilder application) {app.UseIISPlatformHandler app.UseDeveloperExceptionPage app.UseRuntimeInfoPage app.UseFileServer app.UseMvc (ConfigureRoute); app.Run ((context) => {var msg = Configuration [ "message "]; wait for context.Response.WriteAsync (msg);}); } private void ConfigureRoute (IRouteBuilder routeBuilder) {// Home / Index routeBuilder.MapRoute ( "Default ", "{controller = Home} / {action = Index} / {id?} "); } // Entry point of the application. public static void Main (string args) => WebApplication.Run (args); }}

    In the ConfigureRoute method, you canconfigure your routes; you can see that this method should take a parameter of type IRouteBuilder. The purpose of routing is to describe the rules that ASP.NET Core MVC will use to process an HTTP request and find a controller capable of responding to that request.

    Either we run the application in the browser. Once the application is launched, you will see the following output.

     ASP.NET Core - Quick Guide

    You can seea message appear from the app.Run middleware, and the reason we're getting this message is that the MVC middleware has seen this URL. This was a request to the website root, which could not find a controller name or action name in the url. The website root abandoned processing this request and forwarded the request to the next middleware, which is the code app.Run . The road model we specified is silent unlike the default model.

    In the default template, there are defaults to apply if a controller and action name are not found. If a request arrives at the root of the website, the default controller name would be Home. You can replace it with any other controller you like and the default action name can be Index. You can also change the default action if you want, as shown in the following program.

    private void ConfigureRoute (IRouteBuilder routeBuilder) {// Home / Index routeBuilder.MapRoute ( "Default ", "{controller = Home} / {action = Index} / {id?} "); }

    If a request arrives at the root of the website, MVC does not see a controller / action URL type, but it can use these defaults.

    Let us save the Startup.cs file and refresh the browser at the root of the website.

    ASP.NET Core - Quick Guide

    You will now see a response from your controller and you can also go to / home which will invoke the default action, which is index. You can also go to / home / index and now MVC will extract the controller name and action name from the url.

    Let's create another controller by adding another class and call it AboutController .

     ASP.NET Core - Quick Guide

    Let's add some Simple action methods that will return the string as shown in the following program.

    using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace FirstAppDemo.Controllers {public class AboutController {public string Phone () {return "+ 49-333-3333333} public string Country () {return " Germany}}}

    In this controller, you can see two methods of actions - Phone and Country, which will return a phone number and a country name respectively. We will get into sophisticated HTML later. Let's save this file and specify / about / phone at the end of the root URL.

     ASP.NET Core - Quick Guide

    You can see the phone number as in the screenshot above. If you specify / about / country , you will also see the name of the country.

     ASP.NET Core - Quick Guide

    If you navigate to / about , it will fall into the middleware again and access your application. Run the middleware and you will see the following page.

     ASP.NET Core - Quick Guide

    Here the ASP.NET Core MVC accesses AboutController, but does not find a specified action, so it will be byDefault Index and this controller has no Index method and then the request will go to the next middleware.

    ASP.NET Core - Attribute Routes

    In this chapter we are going to learn another approach to routing and that is attribute based routing. With attribute-based routing, we can use C # attributes on our controller classes and on methods internally in those classes. These attributes have data that tells ASP.NET Core when to call a specific controller.

    Example

    Let us take un simple example. Open the FirstAppDemo project and run the application in the browser. When you specify / about , it will produce the following output -

    ASP.NET Core - Quick Guide

    What we want here is that when we specify / about , the app should call the phone running AboutController . Here we can apply some explicit routes for this controller using a Route attribute. This attribute is located in the Microsoft.AspNet.Mvc.

    namespace The following is the implementation of AboutController in which attribute routes are added.

    using Microsoft.AspNet.Mvc; using the system; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace FirstAppDemo.Controllers {[Route ( "about ")] public class AboutController {[Route ( "")] public string Phone () {return "+ 49-333-3333333} [Route (" country ")] stringe public Country () {return "Germany}}}

    Here we want this route to look like approximately and for the Phone action we have specified an empty string, which means we don't need to specify the action to get this method. The user just needs to come to / about. For the Country action, we specified the "country" in the route attribute . Let us register AboutController, refresh your browser and navigate to / about and should give you the Phone action.

     ASP.NET Core Quick Guide

    Let's specify the / about / country . will allow access to this Country action.

     ASP.NET Core - Quick Guide

    If you want a segment of the URL to contain the name of your controller, what you can do is instead use the name of the controller explicitly, you can use a token controller inside the brackets. This tells ASP.NET MVC to use the name of that controller at this position, as shown in the following program.

    using Microsoft.AspNet.Mvc; using system; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace FirstAppDemo.Controllers {[Route (" [controller] " )] public class AboutController {[Route ( "")] public string Phone () {return "+ 49-333-3333333} [Route (" [action] ")] public string Country () {return "Germany}}}

    That way, if you ever rename the controller, you don't have to remember to change the route. The same goes for an action and implicitly there is has a forward slash (/) between the controller and the action. This is a hierarchical relationship between the controller and the action, just as it is in the URL. Let's save again this controller. Most likely you will see the same results.

     ASP.NET Core - Quick guide

    Let's specify the / about / country. This will allow you to access this Country action.

    ASP.NET Core - Quick Guide

    ASP.NET Core - Action Results

    In this chapter we will discusst the results of the action. In the previous chapters, we used simple and straightforward C # classes as controllers. These classes do not derive from a base class, and you can use this approach with MVC, but it is more common to derive a controller from a controller base class provided in the namespace Microsoft.AspNet.Mvc.

    Actions basically return different types of action results. The ActionResult class is the base for all action results. Here is a list of different types of action results and their behavior.

    Name Behavior
    ContentResult Returns a string
    FileContentResult Returns the contents of the file
    FilePathResult Returns the contents of the file
    FileStreamResult Returns the contents of the fitake a dump.
    EmptyResult Returns nothing
    JavaScriptResult Return it for execution
    JsonResult Returns data in JSON format
    RedirectToResult Redirects to the specified URL
    HttpUnauthorizedResult Return HTTP status code 403
    RedirectToRouteResult Redirect to different action / different controller action
    ViewResult Received as response for view engine
    PartialViewR esult Received in response for view engine

    Example 1

    Let's take a simple example by opening the HomeController and derive it from the controller-based class. This base class is located in the Microsoft.AspNet.Mvc namespace. Here is the implementation of the HomeController class.

    using Microsoft.AspNet.Mvc; using the system; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace FirstAppdemo.Controllers {public class HomeController: Controller {public ContentResult Index () {return Content ( "Hello, World! this message comes from the Home Controller using the result of the action ");}}}

    You can now see that the index method returns the ContentResult which is one of the result types and all of these result types ultimately implement an interface, which is the ActionResult .

    In the Index method, we passed a string into the Content method. This Content method produces a ContentResult; this means that the Index method will now return ContentResult.

    Let's save the class HomeController and run the application in the browser. It will produce the following page.

     ASP.NET Core - Quick Guide

    You can now see a response qui doesn't sound different from the answer we had before. It will always be a plain text response.

    Example 2

    Let's take another example. Createsz a new folder in the project and name it Templates . In the Models folder, we want to add a class that can represent an employee.

     ASP.NET Core - Quick Guide

    Enter Employee.cs in the Name field as in the screenshot above. Here the implementation of the Employee class contains two properties.

    using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace FirstAppDemo.Models {public class Employee {public int ID {get; set; } public string Name {get; set}}}

    In the Index action method of HomeController , we want to return an Employee object. Here is the HomeController implementation .

    using FirstAppDemo.Models; using Microsoft.AspNet.Mvc; using system; using System.Collections.Generic; using System.Linq; using System.Threading .Tasks; namespace FirstAppdemo.Controllers {public class HomeController: Controller {Public ObjectResult Index () {var employee = new Employee {ID = 1, Name = "Mark Upston "}; returns a new ObjectResult (employee); }}}

    Now instead of returning the content, we'll return a different type of result which is known as ObjectResult . If we want an ObjectResult, we need to create or instantiate an ObjectResult and pass a model object to it.

    RecordedStream all your files and refresh the browser. You will see the following exit.

     ASP.NET Core - Quick Guide

    ASP.NET Core - Views

    In an ASP.NET Core application MVC, there is no such thing as a page and it also doesn't include anything that matches a page directly when you specify a path in the url. The closest thing to a page in an ASP.NET Core MVC app is called a view.

     ASP.NET Core - Quick guide

    Example

    Now let's take a simple example to understand how it works in our application by modifying the HomeController Index method implementation as shown in the next program.

    using FirstAppDemo.Models; using Microsoft.AspNet.Mvc; using the system; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace FirstAppdemo.Controllers {public class HomeController: Controller {Public ViewResult Index () {var employee = new Employee {ID = 1, Name = "Mark Upston "}; return View }}}

    In HomeController , instead of producing an ObjectResult , let's just return what the View () returns. The View method does not return ObjectResult. It creates a new ViewResult, so we'll also change the return type of the Index method to ViewResult. The View method accepts some parameters here. We will invoke this method without any other parameters. Let us save your file and refresh your browser.

     ASP.NET Core - Quick Guide

    This is because the MVC framework needs to go out and find this view but there is no view at the moment.

    In order for our view output to work properly, let's create this Index.cshtml file in the correct location. So in our project we have toFirst add a folder that will contain all of our views and call it Views. In the Views folder, we'll add another folder for the views associated with our HomeController and call this folder Home. Right click on the Home folder and select Add New Item .

     ASP.NET Core - Quick Guide

    In the left pane, select the MVC display page and enter index.cshtml in the name field and click the Add button.

    Let's add the following code to the index.cshtml file.

    Home

    Welcome!

    This message is from view ...

    You can now see a * .cshtml . It may contain HTML markup and any markup we have in that file will be sent directly to the client. Save this file and refresh your browser.

     ASP.NET Core - Quick Guide

    Now the Home controller via a ViewResult has rendered this view to the clientnt and all the markup that is in that index.cshtml file, this is what was sent to the client.

    Let's go back to the HomeController and the View method. This View method has a few different overloads, and passes the employee model as a parameter.

    using FirstAppDemo.Models; using Microsoft.AspNet.Mvc; using the system; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace FirstAppdemo.Controllers {public class HomeController: Controller {Public ViewResult Index () {var employee = new Employee {ID = 1, Name = "Mark Upston "}; back View (employee); }}}

    The View method which just takes a model object and which will use the default view, which is Index. Here we just want to pass this template information and use this template in Index.cshtml as shown in the following program.

    Home

    Welcome!

    @ Model.Name

    When we use the @ sign in a Razor view , the Razor view engine will treat anything you type as a C # expression. The Razor view has built-in members that we can access in C # expressions. One of the most important members is the model. When you say @Model, you will get the model object you passed into the view from the controller. So here @ Model.Name will display the employee's name in the view.

    Now let's back up all the files. After that, refresh your browser to see the following output.

     ASP.NET Core - Quick Guide

    You can now see the name employee as in the screenshot above.

    ASP.NET Core - Setup Entity Framework

    In this chapter we will install and configure our application to save and read data from a SQL Server database.

    To work with a base data, we will be using Entity Framework, which was recently rewritten to work with the new .NET Framework. If you've worked with EF in the past, you'll see a lot of familiar things.

    To check the LocalDB, go to the View → SQL Server Object Explorer menu option in Visual Studio.

    ASP.NET Core - Quick Guide

    This is a great tool if you need to work with SQL Server because it allows you to explore databases and browse data and even create data in a database. When you first open it, it may take a little while, but it should automatically connect to LocalDB.

    Install Entity Framework

    The first step in using Entity Framework is to install the NuGet Entity Framework package from the NuGet Package Manager or by editing the project.json directly.

    Now let's edit the project.json file directly by adding the following two packages.

     ASP.NET Core - Quick Guide

    The EntityFramework.Commands package helps us perform tasks with Entity Framework like the creating a database schema based on our C # Entity classes and these tasks are available from a command line tool where the logic is in the EntityFramework.Commands package.

    To use this line toolcommand, we need to make an additional entry in the commands section of project.json as shown in the following screenshot.

     ASP.NET Core - Quick Guide

    We just called it "ef " and it will match this EntityFramework.Commands package. We can use this "ef" to access some of the logic available in EntityFramework.Commands.

    The following is the implementation of the project.json file.

    { "version ": "1.0.0 - * ", "compilationOptions ": { "emitEntryPoint ": true}, "dependencies ": { "Microsoft .AspNet.Mvc ": "6.0.0-rc1-final ", "Microsoft.AspNet .Diagnostics ": " 1.0.0-rc1-final ", " Microsoft.AspNet.IISPlatformHandler ": " 1.0.0-rc1-final ", " Microsoft.AspNet.Server.Kestrel " : "1.0.0-rc1-final ", "Microsoft.AspNet.StaticFiles ": "1.0 .0-rc1-final ", "EntityFramework.MicrosoftSqlServer ": "7.0.0-rc1 -final ", " EntityFramework.Commands ": " 7.0.0-rc1-final "} " ccommands ": {" web ": " Microsoft.AspNet.Server.Kestrel "}, " frameworks ": {" dnx451 ": {}, " dnxcore50 ": {}}, "exclude ": [ "wwwroot ", "node_m odules "], "publishExclude ": [ "**. user ", " **. vspscc "]}

    ASP.NET Core - DBContext

    Entity Framework allows you to query, insert, update and delete data at the Using common language runtime (CLR) objects called entities. Entity Framework maps entities and relationships defined in your model to a database. for -

    The main class which is responsible for the interaction with data as objects is DbContext. The recommended way to work with context is to define a class that derives from the DbContext and exposes DbSet properties that represent collections of the entities specified in the context.

     ASP.NET Core - Quick Guide

    Logically, a DBContext maps to a specific database that has a schema that the DBContext understands. And on this DBContext class, you can create properties of type DbSet . Generic type parameter T will be an entity type like Employee is an entity in the FirstAppDemo application.

    Example

    Let's take a simple example, in which we are going to create a DbContext class. Here we need to add a new class in the Models folder and call it FirstAppDempDbContext . Even though this class isn't a template per se, it collects all of our templates so that we can use them with the database.

     ASP.NET Core - Quick Guide

    Inherit your context class from the DbContext class qui is located in the Miscrosoft.Data.Entity namespace. Now implement a DbSet of Employee on this class.

    Eac h DbSet will match a table in the database. If you have an Employee DbSet property and the name of that property is Employees, the Entity Framework will look for an Employees table in your database by default.

    using FirstAppDemo. Templates; using Microsoft.Data.Entity; using the system; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace OdeToFood.Models {public class FirstAppDemoDbContext: DbContext {public DbSet Employees {get; together; }}}

    The implementation is very easy because we only have one model to work with. We only need one property, the DbSet of Employee and we can name this property Employees.

    Now let's insert this classe directly into the controllers, and the controllers could then use FirstAppDemoDbContext to query the database. We will simplify all of this by adding a new class to the HomeController class in which we implement methods to add employee and get employee as shown in the following program.

    using Microsoft. AspNet.Mvc; using FirstAppDemo.ViewModels; using FirstAppDemo.Services; using FirstAppDemo.Entities; using FirstAppDemo.Models; using System.Collections.Generic; using System.Linq; namespace FirstAppDemo.Controllers {public class HomeController: Controller {public ViewResult Index () {var model = new HomePageViewModel using (var context = new FirstAppDemoDbContext ()) {SQLEmployeeData sqlData = new SQLEmployeeData (context); model.Employees = sqlData.GetAll } return View (model); }} public class SQLEmployeeData {private FirstAppDemoDbContext _context {get; together; } public SQLEmployeeData (FirstAppDemoDbContext context) {_context = context; } public void Add (Employee emp) {_context.Add (emp); _context.SaveChanges } public Employee Get (ID int) {return _context.Employees.FirstOrDefault (e => e.Id == ID); } public IEnumerable GetAll () {return _con text.Employees.ToList }} public class HomePageViewModel {public IEnumerable Employees {get; together; }}}

    In the SQLEmployeeData class above, you can see that we have defined the Add method which will add a new employee object to the context and then save the changes. In the Get method, it will return an employee based on ID. Whereas, in the GetAll method, it will return the list of all employees in the database.

    Configuration of Entity Framework services

    To have a usable Entity Framework DBContext, we need to change the configuration of the'application. We will need to add a connection string so that our DBContext knows which server to go to and which database to query.

    Let's go to the AppSettings.json file and add the connection string as shown in the following program.

    { "message ": "Hello, World! cThe message comes from the configuration file ... ", " database ": {" connection ": " Data Source = (localdb) mssqllocaldb; Initial Catalog = F irstAppDemo "}}

    Now let's move on to the Startup class where we need to add some extra services for Entity Framework to work properly. Specifically, there are three things we need to do which are related to Entity Framework:

    All of this can be done by methods which are available as extension methods on IServiceCollection as shown in the following program.

    public void ConfigureServices (IServiceCollection services) {services. AddMvc services.AddEntityFramework () .AddSqlServer () .AddDbContext (option => option.UseSqlServer (Configuration [ "database: connection "])); }

    The following is the full implementation of the Startup.cs file.

    using Microsoft.AspNet.Mvc; using FirstAppDemo.ViewModels; using the Fi rstAppDemo.Services; using FirstAppDemo.Entities; using FirstAppDemo.Models; using System.Collections.Generic; using System.Linq; namespace FirstAppDemo.Controllers {class publique HomeController: Controller {Public ViewResult Index () {var employee = new Employee {Id = 1, Name = "Mark Upston1 "}; using (var context = new FirstAppDemoDbContext ()) {SQLEmployeeData sqlData = new SQLEmployeeData (context); sqlData.Add (employee); } // var employee = new Employee {ID = 1, Name = "Mark Upston "}; back View (employee); }} public class SQLEmployeeData {private FirstAppDemoDbContext _context {get; together; } public SQLEmployeeData (FirstAppDemoDbContext context) {_context = context; } public void Add (Employee emp) {_context.Add (emp); _context.SaveChanges } public Employee Get (ID int) {return _context.Employees.FirstOrDefault (e => e.Id == ID); } public IEnumerable GetAll () {return _context.Employees.ToList }}}

    Now we need to configure the database. One way to setup a database is to use Entity Framework to create the database and it is a two step process-

    The first step

    This involves the following -

    The second step

    This involves the following -

    Let's open the Developer Command Prompt for Visual Studio to run the commands we need to add the migrations and apply the migrations. The easiest way to do this is to go to the root directory of the application.

     ASP .NET Core Quick Guide

    If you are in the folder containing the project.json file, you are in the correct folder. Here we need to run a command called dnvm. It is the .NET version manager that will tell the system which runtime we want to use.

    Now let's use the following command.

    dnvm list

    Youwill see the following output when you press enter.

     ASP.NET Core - Quick Guide

    We have to tell the dnvm that we want to use the specific runtime environments. This will give us access to the command dotnet or to the dnx command we want to run.

    Run the following command.

    dnvm use1.0.0 -rc1-update1 -p

    Press Enter.

     ASP.NET Core - Quick Guide

    dnvm will configure our path and environment variables for include a bin directory that will give us access to this dnx utility. Let's run the command dnx ef .

     ASP.NET Core - Quick Guide

    This is NET runtime environment, using dnx we can invoke the commands we listed in our project.json file. The execution of these commands is generally very easy. When you type dnx ef, you get a help screen. You don't have to remember all of the options. You can see the commands available from Entity Framework commands and there are someat three.

    First, we need to add the migration to run the following command.

    dnx ef migrations add v1

    Press Enter.

     ASP.NET Core - Guquick ide

    Entity Framework will find this context and examine the models that are there. It will know that there is no previous migration and will therefore generate the first migration. Here, v1 is database version 1. It will create a new folder in Solution Explorer and generate code.

     ASP.NET Core - Quick Guide

    A migration is essentially C # code used to generate SQL commands to modify the schema in a database. SQL data.

    using System; using System.Collections.Generic; using Microsoft.Data.Entity.Migrations; using Microsoft.Data.Entity.Metadata; namespace FirstAppDemo .Migrations {public partial class v1: Migration {protected override void Up (MigrationBuilder migrationBuilder) {migrationBuilder.CreateTable (name: "Employeee ", columns: table => new {Id = table.Column (nullable: false) .Annotation (" SqlServer: ValueGenerationStrategy ", SqlServerValueGenerationStrategy.IdentityColumn), Name = table.Column (nullable : true)}, constraints: table => {table.PrimaryKey ( "PK_Employee ", x => x.Id);});} protected override void Down (MigrationBuilder migrationBuilder) {migrationBuilder.DropTable ( "Employee ");}}}

    You can see that this will create a table called Employees.

    ApplyOns these IDs to a database by typing the command " dnx ef database update ".

     ASP.NET Core - Quick Guide

    You can see that the command applied the migration.

    Now let's go to SQL Server Object Explorer and refresh the database, now you can see we have a FirstAppDemo database.

     ASP.NET Core - Quick Guide

    You can also see our Employees table and we can even look at the columns in this table where the ID column is the primary key.

    Right click on the dbo.Employee table and select Show Data.

     ASP.NET Core Quick Guide

    Before launch the application, let's add some data. When we launch the application, we should see some data from the database.

    Let's just add a few lines of data here.

     ASP. NET Core Quick Guide

    Now let's update the index.cshtml file. It shows all the data as a table.

    @model FirstAppDemo.Controllers.HomePageViewModel Home

    Welcome!

    @foreach (employee var in Model.Employees) {}
    @ Html.ActionLink (employee.Id.ToString (), "Details ", new {id = employee.Id}) @employee.Name

    Once the application is executed, it should produce the following output.

     ASP.NET Core - Quick guide

    ASP.NET Core - Razor Layout Views

    In this chapter we are going to understand Razor layout views. Most websites and web applications will want to create pages with some common elements.

    Layout view

    Now let's see what a Layout view is.

     ASP.NET Core - Quick Guide

    Example

    Let's take a simple example.

    If you have multiple views then you will see that all views will contain some amount of duplicate markup. They will all have an opening HTML tag , a head tag and a body tag .

    Even though we don't have a navigation menu in this app, there is a good chance that in a real app it will also be available and we don't want to duplicate this markup in everyview.

    Let's create a Layout view and add the Layout view to a new folder named Shared in the Views folder. This is a conventional folder known to the MVC framework. He knows that the views inside can be used by multiple controllers across the app. Right click on the shared folder and select Add → New Item.

    In the middle pane, select the page of MVC view presentation. The default name here is _Layout.cshtml. Choose the Layout view you want to use when running based on user. Now click on the Add button. This is what you will get by default for your new Layout view.

     ASP.NET Core - Quick Guide

    We want the Layout view to be responsible for managing the head and body. Now, since this view is in a Razor view, we can use C # expressions. We can always add literal text. We have manyby adding a

    < name = "viewport " content = "width = device width " /> @ ViewBag.Title @ DateTime.Now @RenderBody ()

    In the above code, you will see expressions such as RenderBody and ViewBag.Title . When an MVC controller action renders the Index view, and with it a layout page is involved; then the Index view and the HTML it produces will be placed in the Index view.

    This is where the method call to RenderBody exists. We can expect all of our application's content views to appear inside the

    The other expression inside this file is the ViewBag.Title. ViewBag is a data structure that can be added to any property and any data you wantez in the ViewBag. We can add a ViewBag.Title, ViewBag.CurrentDate or any property we want on the ViewBag.

    Now let's go to the index.cshtml file.

    @model FirstAppDemo.Controllers.HomePageViewModel Home

    Welcome!

    @foreach (employee var in Model.Employees) {}
    @ Html.ActionLink (employee.Id.ToString () , "Details ", new {id = employee.Id}) @employee.Name

    Remove markup which we no longer need in the Index view. So we can remove things like the HTML tag and the head tag. We also don't need the opening body element or closing tags as shown in the following program.

    @model FirstAppDemo.Controllers.HomePageViewModel @ {ViewBag.Title = "Homel Layout = "~ / Views / Shared / _Layout.cshtml}

    Welcome!

    @foreach (employee var in Model.Employees) {}
    @ Html.ActionLink (employee .Id.ToString (), "Details ", new {id = employee.Id}) @employee.Name

    We still need to do two things -

    • First, we need to tell the MVC framework that we want to use the Layout view. page from this view.

    • Second, we need to set the appropriate title by adding information in the ViewBag as shown in the code above.

    Let's save all the files and run the application. Once the application is launched you will see the following welcome page.

    ASP.NET Core - Guide quick

    ASP.NET Core - Starting Razor View

    In this chapter we have starting Razor View. The Razor View Engine in MVC has a convention where it will look for any file with the name _ViewStart.cshtml and will run the code inside that file. before running the code in an individual view.

     ASP.NET Core - Quick Guide
    • The code inside the ViewStart file cannot be displayed in the HTML output of a page, but it can be used to remove duplicate code from code blocks to inside the individual views.

    • In our example, if we want each view to use the Layout view that we created in the last chapter, we could put the code to define the Layout view in a ViewStart instead of having the code in each view.

    Example

    Let's take an example simple to see how it works. In our application, we don't want every view to specify that its Layout view is _Layout.cshtml . So right click on the Views folder and select Add → New item .

     ASP .NET Core Quick Guide

    There is a specific template in ASP.NET MVC for a ViewStart page, then select MVC View Start Page in the middle pane. The most important part here is that this file is named _ViewStart.cshtml . Now click on the Add button.

     ASP.NET Core - Quick Guide

    The main use of a ViewStart file is to define the Layout view.

    Now let's move on to dex.cshtml entry and cut the layout line, then add it to the ViewStart file as shown in the following program.

    @ {Layout = "~ / Views / Shared /_Layout.cshtml}

    • When the MVC framework goes to render a view, it will see if there is a ViewStart file somewhere in the folder hierarchy.

    • We have placed _ViewStart directly in our Views folder. This will impact all views of all folders that are in the Views folder, as well as views in the Home folder, as well as the Shared folder, as well as all other dcontrollers ossiers that we may add in the future.

    • If we take ViewStart and put it only in the Home folder, then this little bit of code would only run when we render one of those views in the Home folder .

    • We can even have multiple ViewStart files, so we could have a ViewStart.cshtml here in the Views folder which defines the Layout view for all views.

    • But if we wanted to change this default for all views only in the Home folder, we could have another ViewStart in the Home folder which sets the layout to something else .

    Let's back up all the files and run the application.

    ASP.NET Core - Guide quick

    You will see that your home page looks exactly as it did before, and we still have the Layout view in effect.

    ASP.NET Core - Importing Razor View

    In this chapter we have the Razor View the'import. In addition to the ViewStart file, there is also a ViewImports file that the MVC framework will look for when rendering a view.

    Like the ViewStart file, we can delete ViewImports.cshtml in a folder, and the ViewImports file can influence all views in the folder hierarchy

    ASP.NET Core - Quick Guide
    • This view is new for this version of MVC, in the previous version of MVC we could use a XML configuration file to configure certain aspects of the Razor view engine.

    • These XML files are gone now and we are using code instead.

    • The ViewImports file is a place where we can write code and place common directives to extract the namespaces that our views need.

    • If there are any namespaces that we commonly use in our views, we may have using directives appear once inour ViewImports file instead of having using directives in every view or type in the full namespace of a class.

    Example

    Let's take a simple example to see how to move our using directives into ViewImports . In the Index view, we have a using directive to introduce the FirstAppDemo.Controllers namespace as shown in the following program.

    @using FirstAppDemo.Controllers @model HomePageViewModel @ {ViewBag.Title = "Home}

    Welcome!

    @foreach (employee var in Model.Employees) {}
    @ Html.ActionLink (employee.Id.ToString (), "Details ", new {id = employee.Id}) @employee. Name

    Using directives will allow code generated from the Razor view to compile properly. use directives , the C # compiler cannotWe will not be able to find this Employee type. To see the type of employee, let's remove the using directive from the Index.cshtml file.

    @model HomePageViewModel @ {ViewBag.Title = "Home}

    Welcome!

    @foreach (employee var in Model.Employees) {}
    @ Html.ActionLink (employee.Id.ToString (), "Details ", new {id = employee.Id}) @ employee.Name

    Now run the application.

    ASP.NET Core - Quick Guide

    You will see one of the errors indicating that the type or namespace HomePageViewModel could not be found. This may be because several of your views require the same using directive . So instead of putting it in every view, let's create a view import in the folder Views will add using statements to each view with just right-clicking on the Views folder and selecting Add → New Item.

     ASP .NET Core Quick Guide

    In the middle pane, select the MVC View Imports page.default the name is _ViewImports.cshtml. Just like ViewStart, we can't use this file to render HTML, so let's click the Add button.

     ASP.NET Core Quick Guide

    Now add the using directive in t sound in the _ViewImports.cshtml file as shown below.

    @ using FirstAppDemo.Controllers

    Now all views that appear in this folder or any subfolder will be able to use types from FirstAppDemo.Controllers without specifying this exact using statement. Let’s run at new your application and you will see that the view is working now.

     ASP.NET Core - Quick Guide

    ASP.NET Core - Razor Tag Helpers

    The Tag Helpers allow server-side code to participate in creating and rendering HTML elements in Razor Files. Tag Helpers are a new feature similar to HTML Helpers, which help us render HTML.

    • There are many integrated Tag Helpersres for common tasks, like creating forms, links, loading items, etc. Tag Helpers are created in C # and target HTML elements based on element name, attribute name, or parent tag.

    • For example, the built-in LabelTagHelper can target the HTML

    • If you are familiar with HTML Helpers, Tag Helpers reduce explicit transitions between HTML and C # in Razor views.

    To use Tag Helpers, we need to install a NuGet library and also add an addTagHelper directive to the view (s) that use these tag helpers. Right click on your project in Solution Explorer and select Manage NuGet Packages ....

     ASP.NET Core - Quick Guide

    Find Microsoft.AspNet.Mvc.TagHelpers and click the Install button.

    You will receive the following Preview dialog box.

     ASP.NET Core - Quick Guide

    Click on the OK button.

     ASP.NET Core - Quick Guide

    Click on the I accept button. Once Microsoft.AspNet.Mvc.TagHelpers is installed, navigate to the project.json file.

    { "version ": "1.0.0 - * ", "compilationOptions ": { "emitEntryPoint ": true}, "dependencies ": {" Microsoft.AspNet.Mvc ": " 6.0.0-rc1-final ", " Microsoft .AspNet.Diagnostics ": " 1.0.0-rc1-final ", " Microsoft.AspNet.IISPlatformHandler ": " 1.0.0-rc1-final ", " Microsoft.AspNet.Server.Kestrel ": " 1.0.0-rc1-final ", " Microsoft.AspNet. StaticFiles ": " 1.0.0-rc1-final ", " EntityFramework.MicrosoftSqlServer ": " 7.0.0 -rc1-final ", " EntityFramework.Commands ": " 7.0.0- rc1-final ", " Microsoft.AspNet.Mvc.TagHelpers ": " 6.0.0-rc1-final "}, " commands ": {" web ": " Microsoft.AspNet. Server.Kestrel ", " ef ": " EntityFramework.Commands "}, " frameworks ": {" dnx451 ": {}, " dnxcore50 ": {}}, " exclude ": [" www root ", " node_modules "], " publishExclude ": [" **. user ", " **. vspscc "]}

    In the dependencies section, you will see that " Microsoft.AspNet.Mvc.TagHelpers ": " 6.0.0-rc1-final " is added.

    • Now anyone can create a tag helper, so if you are thinking of a tag helper you have need, you can write your own tag helper.

    • You can place it directly in your app project, but you need to let the Razor view engine know about it. 'tag helper.

    • By default, they are not simply rendered by the client, although these tag helper seem to blend in with the HTML.

    • Razor will call code to process a tag helper; it can remove itself from HTML and it can also add additional HTML.

    • It there are many wonderful things you can do with an acetag sistant, but you need to register your tag wizards with Razor, even Microsoft tag wizards, in order for Razor to spot these tags it lpers in the markup and to be able to call the code that processes the tag helper .

    • The directive to do this is addTagHelper, and you can put it in an individual view, or if you plan to use tag helpers throughout the application , you can use addTagHelper in the ViewImports file as shown below.

    @using FirstAppDemo.Controllers @addTagHelper "*, Microsoft.AspNet.Mvc.TagHelpers "

    The syntax for registering all tag helpers that are in an assembly is to use an asterisk comma (*,) and then the name of the assembly, Microsoft.AspNet.Mvc.TagHelpers . Because the first element here is a type name, this is where we could list an assThere is a specific tag if you only wanted to use one.

    But if you just wanted to take all the tag helpers that are in that, you could just use the asterisk (*) . There are many tag wizards available in the Tag Help Library. Let's take a look at the Index view.

    @model HomePageViewModel @ {ViewBag.Title = "Home}

    Welcome!

    @foreach (employee var in Model.Employees) {}
    @ Html.ActionLink (employee.Id.ToString (), "Details ", new {id = employee.Id}) @ employee.Name

    We already have an HTML helper using the ActionLink to generate an anchor tag that will point to a URL that allows us to 'Access employee details.

    Let's add the Details action in the home controller first as shown in the following program.

    public IActionResult Details (int id) {var context = new FirstAppDemoDbContext SQLEmployeeData sqlData = new SQLEmployeeData (context); var model = sqlData.Get (id); if (model == null) {return RedirectToAction ( "Index ");} return View (model);}

    Now we need to add a view for the Details action. Let's create a new view in the Views → Home folder and call it Details .cshtml and add the following code.

    @model FirstAppDemo.Models.Employee @ Model.Name

    @ Model.Name

    Id: @ Model.Id @ Html.ActionLink ( "Home ", "Index " )

    Now let's launch the application.

     ASP.NET Core - Quick Guide

    When you click on an employee ID, it will bring you to the details view.

    Let's click on the first employee ID.

     ASP.NET Core - Quick Guide

    Now to use the helper tag for this, let's add the following line to the index.cshtml file and remove the HTML helper.

    Details

    The asp-action = "Details " is the name of the action we want to get to. If there is a parameter you want to pass you can use the asp-route tag helper and here we want to include the ID as a parameter so that we can use the asp-route-Id taghelper.

    The Here is the complete implementation of the index.cshtml file.

    @model HomePageViewModel @ {ViewBag.Title = "Home}

    Welcome!

    @foreach (employee var in Model.Employees) {}
    Details @ employee.Name

    Let us run your app again. After running the app, you will see the following page.

    ASP.NET Core - Quick Guide

    Previously we displayed the ID as the link text, but now we displaythe Details text. Now we click on the details and create the correct url now using tag helpers instead of HTML helpers.

     ASP.NET Core - Quick Guide

    Whether you choose to use HTML helpers or tag helpers , it is really a matter of personal preference. Many developers find that helpers tags are easier to create and maintain.

    ASP.NET Core - Razor Editing Form

    In this chapter we will continue to discuss tag wizards. will also add a new feature in our app and give it the ability to edit the details of an existing employee. We will start by adding a link on the side of each employee that will go to an Edit action on the HomeController.

    @model HomePageViewModel @ {ViewBag.Title = "Home}

    Welcome!

    @foreach (employee var in Model.Employees) {}
    @ employee.Name Details Edit

    We don't have the Edit action yet, but we will need an employee ID we can edit. Let's start by creating a new view by right-clicking on the Views → Home folder and selecting Add → New Items .

     ASP.NET Core - Quick Guide

    In the middle pane, select the MVC view page; call Edit.cshtml page. Now click on Add button.

    Add the following code to the Edit.cshtml file.

    @model Employee @ {ViewBag.Title = $ " Edit {Model.Name}}

    Edit @ Model.Name

    For the title of this page, we can say that wewant to edit and then provide the name of the employee.

    • The dollar sign in front of Modify will allow the runtime to replace Model.Name with a value that is in this property like the name of the employee.

    • Inside the form tag, we can use the helpers tag like asp-action and asp-controller. so that when the user submits this form, it goes directly to a specific action of the controller.

    • In this case we want to go to the Edit action on the same controller and we want to explicitly say that for the method on this form it should use an HttpPost .

    • The default method for a form is a GET, and we don't want to edit an employee using a GET operation.

    • In the label tag, we used the asp-for tag helper which indicates that this is a label for the propertyTee Name of the model. This tag helper can configure the Html.For attribute to have the correct value and to set the internal text of this tag to actually display what we want, like the name of the tag. employee.

    Let's go to the HomeController class and add the Edit action which returns the view which gives the user a form to edit a employee, then we'll need a second Edit action that will respond to an HttpPost as shown below.

    [HttpGet] public IActionResult Edit (int id) {var context = new FirstAppDemoDbContext SQLEmployeeData sqlData = new SQLEmployeeData (context); var model = sqlData.Get (id); if (model == null) {return RedirectToAction ( "Index "); } return View (model); }

    First, we need an edit action that will respond to a GET request. You will need an employee ID. The code here will be similar tocode that we have in the Details action. We will first extract the employee data that the user wants to modify. We also need to make sure that the employee actually exists. If it doesn 't exist, we will redirect the user to the Index view. But when an employee exists, we'll render the Edit view.

    We must also reply to the HttpPost that the form will send.

    Let's add a new class in the HomeController .cs as shown in the following program.

    public class EmployeeEditViewModel {[Required, MaxLength (80)] public string Name {get; together; }}

    In the edit action that will respond to the HttpPost will take an EmployeeEditViewModel, but not an employee himself, as we only want to capture the items that are shaped in the Edit file. cshtml.

    The following is the implementation of the Edit action.

    [HttpPost]public IActionResult Edit (int id, EmployeeEditViewModel input) {var context = new FirstAppDemoDbContext SQLEmployeeData sqlData = new SQLEmployeeData (context); employee var = sqlData.Get (id); if (employee! = null && ModelState.IsValid) {employee.Name = input.Name; context.SaveChanges returns RedirectToAction ( "D etails ", new {id = employee.Id});} return View (employee);}

    The edit form must always be delivered from a URL that has an identifier in the URL according to our routing rules, something like / home / edit / 1 .

    • The form will always be sent to this same URL, /home/edit/1.

    • The MVC framework can extract this identifier from the URL and pass it as a parameter.

    • We should always check if the ModelState is valid and also make sure that this employee is in the database and that it is not null before we go '' perform an operationupdate in the database.

    • If none of this is true, we will return a view and allow the user to try again. Although in a real application with concurrent users, if the employee is null then the employee details might be deleted by someone.

    • If this employee doesn 't exist, tell the user that the employee does not exist.

    • Otherwise, check the ModelSt has eaten. If ModelState is not valid, return a view. This corrects the change and makes the ModelState valid.

    • Copy the name of the input view template to the employee checked out from the database and save the changes. The SaveChagnes () method will dump all these modifications into the database.

    The following is the full implementation of HomeController.

    using Microsoft.AspNet.Mvc; usingt FirstAppDemo.ViewModels; using FirstAppDemo.Services; using FirstAppDemo.Entities; using FirstAppDemo.Models; using System.Collections.Generic; using System.Linq; using System.ComponentModel.DataAnnotations; namespace FirstAppDemo.Controllers {public class HomeController: Controller {public ViewResult Index () {var model = new HomePageViewModel using (var context = new FirstAppDemoDbContext ()) {SQLEmployeeData sqlData = new SQLEmployeeData (context); model.Employees = sqlData.GetAll } return View (model); } publi c IActionResult Details (int id) {var context = new FirstAppDemoDbContext SQLEmployeeData sqlData = new SQLEmployeeData (context); var model = sqlData.Get (id) if (model == null) {return RedirectToAction ( "Index "); } return View (model); } [HttpGet] public IActionResult Edit (int id) {var context = new FirstAppDemoDbContext SQLEmployeeData sqlData = new SQLEmployeeData (context); var model = sqlData.Get (id); if (model== null) {return RedirectToAction ( "Index "); } return View (model); } [HttpPost] public IActionResult Edit (int id, EmployeeEditViewModel entry) {var context = new FirstAppDemoDbContext SQLEmployeeData sqlData = new SQLEmployeeData (context); employee var = sqlData.Get (id); if (employee! = null && ModelState.IsValid) {employee.Name = input.Name; context.SaveChanges return RedirectToAction ( "Details ", new {id = employee.Id}); } return View (employee); }} public class SQLEmployeeData {private FirstAppDemoDbContext _context {get; together; } public SQLEmployeeData (FirstAppDemoDbContext context) {_context = context; } public void Add (Employee emp) {_context.Add (emp); _context.SaveChanges } public Employee Get (ID int) {return _context.Employees.FirstOrDefault (e => e.Id == ID); } public IEnumerable GetAll () {return _context.Employees.ToList }} public class HomePageViewModel {public IEnumerable Employees {get; together; }} public class EmployeeEditViewModel {[Required, MaxLength (80)] public string Name {get; together; }}}

    Let's compile the program and run the application.

     ASP.NET Core Quick Guide

    We now have an edit link available; let's edit Josh's details by clicking the Edit link.

     ASP.NET Core - Quick Guide

    Let's change the name to Josh Groban.

     ASP.NET Core - Quick Guide

    Click on Save button.

    ASP.NET Core - Quick Guide

    You can see the name has been changed to Josh Groban like in the screenshot above. Now let's click on the Home link.

    ASP.NET Core - Quick Guide

    On the home page you will now see the updated name.

    ASP.NET Core - Identity Overview

    In this chapter, we briefly have the ASP.NET Core Identity framework. The ASP.NET Core Identity framework is used to implement authentication by form. There are many options to identify your users including Windows Authentication and all third party identity providers like Google, Microsoft, Facebook and GitHub etc.

    • The identity framework is another dependency that we will add to our application in the project.js file.

    • This framework we allows adding functionality where users can register and log in with a local password.

    • The framework also supports authentication at two factors, third party identity providers and other features.

    • We will focus on the scenarios in which a user can register, log in and log out.

    To do this we need to create a User entity and this class will inherit from a base class in the Identity framework and the base class we give our standard user properties like username and email address.

     ASP.NET Core - Quick Guide
    • We can include as many additional properties as we want in this class to store information about ourusers.

    • We need to take this User class and plug it into a UserStore class provided by Identity framework.

    • The UserStore is the class our code will talk to to create users and validate user passwords.

    • Ultimately, a UserStore will talk to a database. The Identity framework supports the Entity Framework and all databases that can work with the Entity Framework.

    • But you can implement your own UserStore to work with any data source.

    • In order to work properly with Entity Framework, our User class will also connect to an IdentityDb class.

    • This is one that uses a DBContext Entity Framework to do the actual database work.

    • We will need to include this IdentityDb in our application by inheritingof our existing IdentityDb DataContext class instead of the Entity Framework's DBContext.

    • These are IdentityDb and UserStore working together to store user information and validate user passwords, hashed passwords that are in the database.

    There are two elements of the ASP.NET Core Identity Framework that we need to know

     ASP.NET Core - Quick guide

    SignInManager

    It 's one of the two elements of the identity framework -

    • As the name suggests, the SignInManager can login a user once we have validated the password.

    • We can also use this manager to disconnect a user.

    • With forms authentication, connection and disconnection is done by managing a cookie.

    • When we tell the SignInManager to connect a user, the manager issues a cookie to the user's browser, and the browser will send this cookie on each subsequent request. This helps us to identify this user.

    Identity Middleware

    This is the second element of the framework -

    • Read the cookie sent by the SignInManager and identify the user, e This happens in the last element of the framework, the identity middleware.

    • We will need to configure this middleware in our application pipeline to process the cookie set by the SignInManager. We will also see other features of this middleware in the next chapters.

    ASP.NET Core - Authorize Attribute

    In this chapter, we will discuss the authorization attribute. So far in our app we have allowed anonymous users to do anything. They can edit employee details and view details, but we don't have anyhave the functionality to create a new employee. Let's add the authoring functionality first, and then we will restrict user access using the Authorize attribute.

    We need to start by creating a new MVC View page in the Views → Home folder and call it Create.cshtml then add the following code.

    @model Employee @ {ViewBag.Title = "Create}

    Create

    @using (Html.BeginForm ()) {@ Html.LabelFor (m => m.Name) @ Html.EditorFor (m => m.Name) @ Html.ValidationMessageFor (m => m.Name)}

    We will now add the d method 'action in HomeController for POST and GET, as shown in the following program.

    [HttpGet] public ViewResult Create () {return View } [HttpPost] public IActionResult Create (EmployeeEditViewModel model) {if (ModelState.IsValid) {var employee = new Employee employee.Name = model.Name; var context = new FirstAppDemoDbContext SQLEmployeeData sqlData = new SQLEmployeeData (context); sqlData.Add (employee); return RedirectToAction ( "Details ", new {id = employee.Id}); } return View }

    Let's add a link to Create View in the Index.cshtml file as shown in the following program.

    @model HomePageViewModel @ {ViewBag.Title = "Home}

    Welcome!

    @foreach (employee var in Model.E employees ) {}
    @employee.Name Details Edit
    Create

    Run the application; you will see the following page.

     ASP.NET Core - Quick Guide

    On the home page, you will see the Create link. When you click the Create link, it will take you to the Create view.

     ASP.NET Core - Quick Guide

    Enter a name in the Name field and clickUse the Save button.

     ASP.NET Core - Quick Guide

    You will now see the detail view of the newly added employee. Let's click on the Home link.

     ASP.NET Core - Quick Guide

    In this application, each user can create, modify an employee and everyone can see the detailed view. We want to change this behavior so that in the future, anonymous users can only see the list of employees on the home page, but any other action requires the user to identify and log in. We can do this with Allow attribute .

    You can place the Authorize attribute on a controller or on individual actions inside the controller.

    [Authorize] public class HomeController: Controller {//. ...}

    • When we place the Authorize attribute on the controller itself, the authorize attribute applies to all actions inside.

    • The MVC framework does notwill not allow a request to reach an action protected by this attribute unless the user passes an authorization check.

    • By default, if you don't use any other parameters, the only check the Authorize attribute will perform is a check to make sure the user is logged in so that we know their identity.

    • But you can use parameters to specify any custom permission policy you like.

    • There is also an AllowAnonymous attribute. This attribute is useful when you want to use the Allow attribute on a controller to protect all actions inside, but there is that single action or one or two actions that you want to unprotect and allow anonymous users to 'achieve this specific action.

    [AllowAnonymous] public ViewResult Index () {var model = new HomePageViewModel using (var context = new FirstAppDemoDbContext ()) {SQLEmployeeData sqlData = new SQLEmployeeData (context); model.Employees = sqlData.GetAll } return View (model); }

    Let's try these attributes in our application. In the running application, an anonymous user can edit an employee.

     ASP.NET Core - Quick Guide

    We want to change that and force users to login and login before we can edit a employee. Now on to the HomeController. Here we will limit access to one or two actions. We can always set the Authorize attribute on the specific actions that we want to protect. We can also set the Authorize attribute on the controller. itself, and this Authorize attribute is in the Microsoft.AspNet.Authorization namespace.

    We will now use the Authorize attribute and force users to login to enter this controller except forthe home page as shown in the following program.

    [Authorize] public class HomeController: Controller {[AllowAnonymous] public ViewResult Index () {var model = new HomeP ageViewModel using (var context = new FirstAppDemoDbContext ()) {SQLEmployeeData sqlData = new SQLEmployeeData (context); model.Employees = sqlData.GetAll } return View (model); } Public details IActionResult (int id) {var context = new FirstAppDemoDbContext SQLEmployeeData sqlData = new SQLEmployeeData (context); var model = sqlData.Get (id); if (model == null) {return RedirectToAction ( "Index "); } return View (model); } [HttpGet] public IActionResult Edit (int id) {var context = new FirstAppDemoDbContext SQLEmployeeData sqlData = new SQLEmployeeData (context); var model = sqlData.Get (id); if (model == null) {return RedirectToAction ( "Index "); } return View (model); } [HttpPost] public IActionResult Edit (int id, Emplo entryyeeEditViewModel) {var context = new FirstAppDemoDbContext SQLEmployeeData sqlData = new SQLEmployeeData (context); employee var = sqlData.Get (id); if (employee! = null && ModelState.IsValid) {employee.Name = input.Name; context.SaveChanges return RedirectToAction ( "Details ", new {id = employee.Id}); } return View (employee); } [HttpGet] public ViewResult Create () {return View } [HttpPost] public IActionResult Create (EmployeeEditViewModel model) {if (ModelState.IsValid) {var employee = new Employee employee.Name = model.Name; var context = new FirstAppDemoDbContext SQLEmployeeData sqlData = new SQLEmployeeData (context); sqlData.Add (employee); return RedirectToAction ( "Details ", new {id = employee.Id}); } return View }}

    The home page or the Index.cshtml file that displays the list of employees has the AllowAnonymous attribute. Now let's launch your application.

     ASP.NET Core - Quick Guide

    Press the F12 key which will open the toolsdevelopment . Now go to Network tab .

     ASP.NET Core - Quick Guide

    There are a few things we want to look at in the dev tools, so we can see how things work . When you click on the Edit link, you will see a blank page.

     ASP.NET Core - Quick Guide

    If you look at the developer tools, you will see that the HTTP status code returned by the server was a 401 status code .

     ASP.NET Core - Quick guide

    The 401 status code tells the browser that the request was not allowed because it did not have valid credentials. This tells us that the Authorize attribute is working .

    Similarly, when you click the Create link on the homepage, you will see the same error shown in the following screenshot.

     ASP.NET Core - Quick Guide
    • Here the problem is that the User is left on a blank page and unless you have the developer tools open, they may not know it wasan authentication problem.

    • This is where the Identity framework can step in and help.

    • The Identity framework can detect when an application element wants to return the status 401 code because the user is not authorized to access it, and the Identity frame can turn this into a login page and allow the user to overcome this problem.

    • We'll see how that works once we've installed and configured the Identity framework.

    • But for now, we can see that the Au thorize attribute is working.

    ASP.NET Core - Identity Configuration

    In this chapter we will install and configure the identity framework, this which just takes a little work. If you go to Visual Studio and create a new ASP.NET Core app, and choose the Full Web App template with authenticationdefined on individual user accounts, this new project will include all the elements of the Identity framework set up for you.

     ASP.NET Core - Quick guide

    We started with an empty project, now we are going to set up the identity framework from scratch, which is a good way to find out about all the parts of the model of full application, as it can be confusing if you haven't gone through all the codes in detail.

    To start, we'll need to install the dependency, which is Microsoft.AspNet.Identity . We will do this by installing Microsoft.AspNet.Identity.EntityFramework , then implementing the Identity framework which works with Entity Framework.

    • If we take a dependency on Identity.EntityFramework, the package includes the Identity package.

    • If you create your own data stores, you can only work with the Identity package.

    • Once our ddependencies installed, we can create a client user class with all the information we want to store about a user.

    • For this application we are going to inherit from a class provided by the Identity framework and this class will give us all the essentials like the Username property and a place to store the hashed passwords.

     ASP.NET Core - Quick Guide
    • We will also need to modify our FirstAppDemoDbContext class to inherit f from the IdentityDb class from Identity Framework.

    • IdentityDb gives us everything we need to store as user information with Entity Framework. Once we have configured a User class and a DBContext , we will need to configure the identity services in the application with the ConfigureServices Method of the Startup class.

    • Just like when we had to addservices To support the MVC framework, the Identity framework needs services added to the application to work.

    • These services include services such as the UserStore service and the SignInManager .

    • We will inject these services into our controller to create users and issue cookies at the appropriate time.

    • Finally, during the Startup Configure method, we will need to add the Identity middleware.

    • This middleware will not only help turn cookies into a user identity, but also ensure that the user does not make them see a page empty with a 401 response.

    Now let's follow the steps below.

    Step 1 - We need to continue adding a dependency on the Identity framework. Let's add the Microsoft.AspNet.Identity.EntityFramework dependency in the project.json file. This will include tous the other necessary identity packages that we need.

    { "version ": "1.0.0 - * ", "compilationOptions ": { "emitEntryPoint ": true}, " dependencies ": {" Microsoft.AspNet.Mvc ": " 6.0.0-rc1-final ", " Microsoft.AspNet.Diagnostics ": " 1.0.0-rc1-final ", "Microsoft.AspNet.IISPlatformHandler ": "1.0.0-rc1-final ", "Microsoft.AspNet.Server.Kestrel ": "1.0 .0-rc1-final ", "Microsoft.AspNet .StaticFiles ": " 1.0.0-rc1-final ", " EntityFramework.MicrosoftSqlServer ": " 7.0.0-rc1-final ", " EntityFramework.Commands ": " 7.0.0 -rc1-final ", " Microsoft.AspNet.Mvc.TagHelpers ": " 6.0.0-rc1-final ", " Microsoft.AspNet .Identity.EntityFramework ": " 3.0.0-rc1 -final "}, " commands ": {" web ": " Microsoft.AspNet.Server.Kestrel ", " ef ": " EntityFramework.Commands "}, " frameworks ": {" dnx451 ": {}, " dnxcore50 ": {}}, " exclude ": [" wwwroot ", "node_modules "], " publishExclude ": [" **. user ", " **. vspscc "]}

    Step 2 - Save this file. Visual Studio restores the packages and now we can add our User class. Let's add the User class by clicking with the button right on the Models folder and selecting Add → Class.

     ASP.NET Core - Quick Guide

    Call this class user and click the Add button as in the screenshot above. In this class you can add properties to contain all the information you want. you want to store on a user.

    Step 3 - Let's derive the User class from a class provided by the Identity Framework. This is the class IdentityUser which is in the Identity.EntityFramework namespace.

    using Microsoft.AspNet.Identity.EntityFramework; using system; using System.Collections.Generic ; using System.Linq; using System.Threading.Tasks; namespace FirstAppDemo.Models {public class User: IdentityUser {}}

    Step 4 - Now let's go to IdentityUser, hover the cursor over this symbol and press F12 to see the data view from Visual Studio.

    #region Assembly Microsoft.AspNet.Identity.EntityFramework, Version = 3.0.0.0, namespace Microsoft.AspNet.Identity.EntityFramework {public class IdentityUser: IdentityUser { public IdentityUser public IdentityUser (string userName); }}

    Step 5 - You can see that IdentityUser is derived from IdentityUser from the string. You can change the type of the primary key by deriving from IdentityUser and specifying our generic type parameter. You can also store things with a primary key which is ideally an integer value.

    Step 6 - Now let's place the cursor on IdentityUser of string and press F12 again to go to the data view.

     ASP.NET Core - Quick Guide

    You mayntaining see all the information relating to a user by defau lt. The information includes the following -

    • Fields that we will not be using in this application, but are available.

    • The identity framework can track the number of failed login attempts for a particular user and can lock out that account over a period of time.

    • Fields to store the PasswordHash, PhoneNumber. The two important fields we will be using are the PasswordHash and the UserName.

    • We will also implicitly use a user's primary key and ID property. You can also use this property if you need to search for a specific user.

    Step 7 - We now need to make sure the User is included in our DBContext. So, let's open the FirstAppDemoDBContext thatwe have it in our app, and instead of deriving it directly from DBContext, which is the built-in base Entity Framework class, we now need to derive it from IdentityDbContext.

    using Microsoft.AspNet.Identity.EntityFramework; using Microsoft.Data.Entity; namespace FirstAppDemo.Models {public class FirstAppDemoDbContext: IdentityDbContext {public DbSet Employees {get; together; } override void OnConfiguring (DbContextOptionsBuilder optionsBuilder) {optionsBuilder.UseSqlServer ( "Data Source = (localdb) MSSQLLocalDB; Initial Catalog = FirstAppDemo; Integrated Security = True; Connect Timeout = 30; Encrypt = False; TrueServer; ApplicationFailnetWriteWrite protected = protected = False "); }}}

    Step 8 - The IdentityDbContext class is also in the Microsoft.AspNet.Identity.EntityFramework namespace and we can specify the type of user that 'she muststore. This way any extra fields we add to the User class get into the database.

    • The IdentityDbContext provides additional DbSets, not only for storing a user but also information on user roles and claims.

    • Our User class is now ready. Our FirstAppDemoDbContext class is configured to work with the Identity framework.

    • We can now go to Configure and ConfigureServices to configure the Identity framework.

    step 9 - Now let's start with ConfigureServices . In addition to our MVC services and our Entity Framework services, we need to add our identity services. This will add all the services that the Identity framework relies on to do its job.

    public void ConfigureServices (IServiceCollection services) {services.AddMvc services.AddEntityFramework () .AddSqlServer () .AddDbContext (option => option.UseSqlServer (Configuration [ "database: connection "])); services.AddIdentity () .AddEntityFrameworkStores }

    • The AddIdentity method takes two parameters of generic type - the user entity type and the role entity type.

    • The two generic type parameters are the types of our user - the User class we just created and the Role class we want to work with. We will now use the built-in IdentityRole. This class is located in the EntityFramework namespace.

    • When we use Entity Framework with Identity, we also need to invoke a second method - AddEntityFrameworkStores.

    • The AddEntityFrameworkStores method confiwill manage services like the UserStore, the service used to create users and validate their passwords.

    Step 10 - The next two lines are all we need to configure the application services.

    services.AddIdentity () .AddEntityFrameworkStores

    Step 11 - We also need to add the middleware. Where we insert the middleware is important because if we insert the middleware too late into the pip eline, it will never have a chance to process a request.

    And if we need authorization checks in our MVC controllers, we need to have the Identity middleware inserted before the MVC framework to ensure that cookies and also 401 errors are handled successfully.

    public void Configure (IApplicationBuilder application) {app.UseIISPlatformHandler app.UseDeveloperExceptionPage app.UseRuntimeInfoPage app.UseFileServer app.UseIdentity app.UseMvc (ConfigureRoute); app.Run ((context) => {var msg = Configuration [ "message "]; wait for context.Response.WriteAsync (msg);}); }

    Step 12 - The place where we insert the middleware is where we will add the Identity middleware. The following is the full implementation of the Startup.cs file.

    using Microsoft.AspNet.Builder; using Microsoft.AspNet.Hosting; using Microsoft.AspNet.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Configuration; using FirstAppDemo.Services; using Microsoft.AspNet.Routing; using the system; using FirstAppDemo.Entities; using Microsoft.Data.Entity; using FirstAppDemo.Models; using Microsoft.AspNet.Identity.EntityFramework; namespace FirstAppDemo {public class Startup {public Startup () {var builder = new ConfigurationBuilder () .AddJsonFile ( "AppSettings.json "); Configuration = constructor.Build } Public IConfiguration configuration {get; together; } // This method is called by the runtime. // Use this method to add services to the container. // For more information on configuring your application, // visit http: //go.microsoft.com/fw/? LinkID "= 398940 public void ConfigureServices (IServiceCollection services) {services.AddMvc services.AddEntityFramework () .AddSqlServer () .AddDbContext (option => option.UseSqlServer (Configuration [ "database: connection "])); services.AddIdentity () .AddEntityFra meworkStores } // This method is called by the runtime. // Use this method to configure the HTTP request pipeline public void Configure (IApplicationBuilder application) {app.UseIISPlatformHandler app.UseDeveloperExceptionPage app.UseRuntimeInfoPage app.UseFileServer app.UseIdentity app.UseMvc (ConfigureRoute); app.Run ((context) => {var msg = Configuration [ "message "]; wait for context.Response.WriteAsync (msg);}); } private void ConfigureRoute (IRouteBuilder routeBuilder) {// Home / Index routeBuilder.MapRoute ( "Default ", "{controller = Home} / {action = Index} / {id?} "); } // Entry point of the application. public static void Main (string args) => WebApplication.Run (args); }}

    Step 13 - Now let's move forward by building the application. In the next chapter, we need to add another Entity Framework migration to make sure we have the identity schema in our SQL Server database.

    ASP.NET Core - Identity Migrations

    In this chapter, we will discuss identity migration. In ASP.NET Core MVC, the authentication and 'Identity are configured in the Startup.cs file.

    public void ConfigureServices (IServiceCollection services) {services.AddMvc services.AddEntityFramework () .AddSqlServer () .AddDbContext option. UseSqlServer (Configuration [ "database: connection "])); services.AddIdentity () .AddEntityFrameworkStores }

    Anytime you make a change to any of your entity classes or make a change to your DBContext derived class, you will likely need to create a new migration to apply to the database and bring the schema in sync with what's in your code.

    This is the case in our application as we now derive our FirstAppDemoDbContext class from the IdentityDbContext class, and it contains its own DbSets, and it will also create a schema to store allinformation about the entities it manages.

    using Microsoft.AspNet.Identity.EntityFramework; using Microsoft.Data.Entity; namespace FirstAppDemo.Models {public class FirstAppDemoDbContext: IdentityDbContext {public DbSet Employees {get; together; } override void OnConfiguring (DbContextOptionsBuilder optionsBuilder) {optionsBuilder.UseSqlServer ( "Data Source = (localdb) MSSQLLocalDB; Initial Catalog = FirstAppDemo; Integrated Security = True; Connect Timeout = 30; Encrypt = False; TrueServer; ApplicationFailnetWriteWrite protected = protected = False "); }}}

    Now let's open the command prompt and verify that we are in the location where the project.json file is for our project.

     ASP.NET Core Quick Guide

    We can also get Entity Framework commands by typing dnx ef .

     ASP.NET Core - Quick Guide

    Our project.json file has a section that maps this “ef” keyword to EntityFramework.Co commandsmmands.

    "orders ": { "web ": "Microsoft.AspNet.Server.Kestrel ", "ef ": "EntityFramework. Commands "}

    We can add a migration from here. We also need to give the migration a name. Let's use v2 for version 2 and hit enter.

     ASP.NET Core - Quick Guide

    Once the migration is complete, you will have a v2 file in your migrations folder.

     ASP.NET Core - Quick guide

    We now want to apply this migration to our database by running the "dnx ef database update" command.

     ASP.NET Core - Quick Guide

    Entity Framework will see that a migration needs to be applied and will run this migration.

    If you enter SQL Server Object Explorer, you will see the Employee table we created earlier. You will also see additional tables that need to store users, claims, roles, and mapping tables that correspond users to specific roles.

     ASP.NET Core - Quick Guide

    All these tables are linked toentities provided by the Identity framework.

    Let's take a look at the user table .

     ASP.NET Core - Quick Guide

    You can now see that the columns of the AspNetUsers table include columns to store all the properties we saw on the identity user that we inherited, and its fields like User Name and PasswordHash. So, you used some of the services of 'Identity built-in as they also contain the ability to create a user and validate a user's password.

    ASP.NET Core - User Registration

    In In this chapter we will discuss user registration. Now we have a working database and it is time to start adding some functionality to the application. We have also configured our application and we have a basic schema Now let's go back to the home page of the application.

     ASP.NET Core - Quick Guide

    Ouvre the development tools by pressing F12 then click on the Modify link. Previously, when we clicked on the Edit link, the MVC framework detected the presence of the Authorize attribute and returned a 401 status code because the user was not logged in.

     ASP.NET Core - Quick Guide

    You will now see that we get a message on the configuration file screen.

    Now let's go to the developer tools.

     ASP.NET Core - Quick Guide
    • You will see that the browser has requested the edit page, and the MVC framework has decided that the user is not allowed to view this resource.

    • So somewhere in the MVC framework, a 401 status code was generated.

    • We now have the Identity middleware in place. The Identity middleware examines this 401 status code that is going to be sent to the user and replaces it with a 302 status code, which is a status code. 'redirect state.

    • The Identity framework knows that the usersateur will have to try to log in before he can access this resource.

    • The Identity framework directed us to this URL, as we can see in the address bar - / Account / Login.

    • This is a configurable endpoint with the Identity framework, inside the Startup when you register these services and middleware. There are different options you can set and one of the options is to change the login url.

    • By default, the URL will be / Account / Login. Currently we don 't have an account controller so ultimately we want to create an account controller and allow a user to log in.

    • But before users can even log in, they will need to register on the site and register their usernames and passwords.

    • Login and registration features can makepart of an account controller.

    Now let's go ahead and add a new class in the Controllers folder, and call it AccountController. We will derive this from the base Controller class of the MVC framework.

    using Microsoft.AspNet.Mvc; using the system; using System.Collections.Generic; using System.ComponentMo del.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace FirstAppDemo.Controllers {public class AccountController: Controller {}}

    • We are now going to have to set up a feature allowing a user to s ' register on this site.

    • It will look a lot like an edit form.

    • When the user wants to register, we will first display a form that allows them to fill in the required information. They can then download this form son the site.

    • This information is then saved in the database.

    Now let us create the action that will return a view when we go to /account/register.

    public class AccountController: Controller {[HttpGet] public ViewResult Register () {return View }}

    We don 't need to search for anything, the user will provide all the information we need. Before we create the ViewModel for this view, we need to decide what information the view will display. We also need to decide what information we will need to receive from the user?

    Let's create a view model for this scenario by adding a new class in the AccountController.cs file and calling it RegisterViewModel.

    Let's create some properties which will contain the username, password and also the ConfirmPassword user in the ttyping twice and making sure the two passwords match as shown in the following program.

    public class RegisterViewModel {[Required, MaxLength (256)] public string Username {get; together; } [Required, DataType (DataType.Password)] public string Password {get; together; } [DataType (DataType.Password), Compare (nameof (Password))] public string ConfirmPassword {get; together; }}

    In the class above, you can see some annotations that can help us validate this model. The username is required here and if you look at the database schema, the column to contain a username is 256 characters long.

     ASP.NET Core - Quick guide
  • We will also apply a MaxLength attribute here.

  • A password will be required, and when we make an entry for this password we want the entry type to be Type password afin that the characters do not appear on the screen.

  • The Confirm Password will also be the DataType password, then there will be an additional compare attribute. We will compare the ConfirmPassword field with this other property that we can specify, which is the Password field.

  • Now let's create the view we need. We will need to add a new folder to the views and call it Account, so all the views linked to the AccountController will be added to this folder.

     ASP.NET Core - Quick Guide

    Now right click on the Account folder and select Add → New Item.

     ASP.NET Core - Quick Guide

    In the middle pane, select the MVC display page and name it Register .cshtml, then click the Add button.

    Remove any existing codes from the Register.cshtml file and add the following code.

    @model RegisterViewModel @ {ViewBag.Title = "Register}

    Register

    • You can now see that we have specified the model as the RegisterViewModel we just created.

    • We are also going to set the title of this page using the ViewBag and we want the title to be Register.

    • We also need to create a form containing the Username, Password, and ConfirmPassword fields.

    • We have also included a

    • We can show all errors in the summary area, or we cansay ValidationSummary.ModelOnly and the only errors that will appear from validating the model inside the summary will be the validation errors associated with the model and not a specific property of that model.

    • In other words, if the users don't fill in their username, but the username is required, there will be an error validation for that specific property.

    • But you may also generate model errors which are not associated with a specific property and which will appear in this ValidationSummary.

    • In a tag we have labels and entries for all the different fields we have in our ViewModel.

    • We need a label for the username, an entry for the username and also validation messages for the username. 'user.

    • The other two the proprieties that we need to enter by the user are the same and will have a label and an entry and a scope for the password and a tag and an entry and a scope for ConfirmPassword.

    • We don 't need to specify the input types for password and confirmation password, because asp for the tag helper will make sure to set this type of entry as the password for us.

    • At the end we must have the button that says Register . When user clicks this button, we will resend the form to the controller.

    In the AccountController, we also need to implement an HttpPost Register action method. Let's go back to the AccountController and add the following Register action as follows -

    [HttpPost] public IActionResult Register (RegisterViewModel model) {}

    This method action will return an IActionResult. This will receive a RegisterViewModel. Now we need to interact with the Identity framework to make sure the user is valid, to tell the Identity framework to create this user, and then since they just created the account, go ahead and sign them in. We will look at implementing all of these steps in the next chapter.

    ASP.NET Core - Create User

    In this chapter we will discuss how to create a user. To continue, we need to interact with the Identity framework to make sure the user is valid, then create this user, then continue and login.

    • There are two basic services of the Identity framework, one is the UserManager and the other is the SignInManager.

    • We need to inject these two services into our controller. With this we can call the appropriate APIs when we need to create a user.r or log in a user.

    • Let's add private variables for SignInManager and UserManager, then add a constructor in your AccountController, which will take two UserManager parameters of type User and one SignInManager of type User.

    private SignInManager _signManager; Private UserManager _userManager; AccountController public (UserManager userManager, SignInManager signManager) {_userManager = userManager; _signManager = signManager; }

    • We are going to continue with the POST action method of AccountController and one of the first checks we should always make inside the post action is to check if our ModelState is valid.

    • If ModelState is valid then we know that the user gave us a username and password and confirmed the password; if not, we have to ask them to fofill in the correct information.

    • Here is the implementation of the Save action.

    [HttpPost] public Task Register (RegisterViewModel model) {if (ModelState.IsValid) {var user = new User { UserName = model.Username}; var result = wait _userManager.CreateAsync (user, model.Password); if (result.Succeeded) {wait _signManager.SignInAsync (user, false); return RedirectToAction ( "Index ", "Home "); } else {foreach (var error in result.Errors) {ModelState.AddModelError ( "", error.Deion); }}} return View }

    • If our ModelState is valid, we need to talk to the Identity framework. We also need to create a new instance of our User entity and copy our model.Username entry into the UserName property of the User entity.

    • But we are not going to copy the password because there is no place for stoCheck the password in plain text in the User entity. Instead, we'll pass the password directly to the Identity framework, which will hash the password.

    • So we have a userManager. Create an Async method where we need to pass the username, so that we can save that user's password.

    • This Async method returns a result that tells us if the instance succeeded or failed and if it failed, this will give us some of the possible reasons for its failure.

    • If the result is successful, we can connect the user who just created an account and then ask the SignInManager to sign this user. Now redirect the user to the home page and you will now be authenticated.

    • If the result was not successful, we should try to tell the user why, a d the result coming back from UserManager has ae collection of errors that we can iterate and add these errors into ModelState. These errors will be available in the view for tag wizards such as validation tag wizards, to display information about the page.

    • In ModelState.AddModelError, we can provide a key to associate an error with a specific field. We will also use an empty string and add the deion of the error that was provided.

    Let's backup all the files and run the application and go to / account / registry .

     ASP.NET Core - Quick Guide

    Let's enter a very simple 5 character username and password.

     ASP.NET Core - Quick Guide

    Now click on the Save button.

     ASP.NET Core - Quick Guide

    Default , the Identity framework tries to enforce certain rules around passwords.

    Passwords must be at least 6 characters long, one character must be lowercase, one must be uppercase and it must be a non-numeric character.

    The la rThe reason these errors show up here is because we have a mary commit sum on the page that catches the errors that come back from the userManager.CreateAsync result.

    Now that we know a little more about the password rules, let us try to create a sufficiently complex password and click on register.

     ASP.NET Core - Quick Guide

    You will now see the home page. This means that the operation worked . Now let's move on to SQL Server Object Explorer.

     ASP.NET Core - Quick Guide

    Right-click on the dbo.AspNetUsers table and select Show data .

    ASP.NET Core - Quick Guide

    Now you can see that the user was created successfully and you can also see a new record in the table Users. You may also see a hashed password value as well as a username and this is the username we registered with mark.upston .

    ASP.NET Core - Login and Deconnexion

    In this chapter we have the functionality of connection and disconnection. The disconnection is rather simple to implement compared to the connection. Let's continue with the Layout view because we want to create a user interface with links. This will allow a logged in user to log out and display the username as well.

    < name = "viewport " content = "width = device-width " /> @ ViewBag.Title @ DateTime.Now @RenderBody ()

    • For an anonymous user, we will display a login link.

    • All the information you need to create this user interface is available in the context of the Razor view.

    • First, let's add the System .Security.Claims namespace in your layout view.

    @using System.Security.Claims < name = "viewport " content = "width = device-width " /> @ ViewBag.Title @if (User.IsSignedIn ()) {@ User.GetUserName ()} el { Login Register } @ DateTime.Now @RenderBody ()

    • There is a User property that is available in every Razor view and we want to create one user interface that will display the name of the logged in user. An IsSignedIn extension method is also available here.

    • We can invoke this method and if it returns true, this is where we can place markup display username, display a logout button.

    • Now if the user is logged in, we can display the user 's username using the GetUserName helper method .

    • We will need to create a logout button in a form, which will be posted to the web server. This must be done as it will create some unsavory conditions, if you allow a simple GET REQUEST to allow a user to exit.

    • We will force this to be a message, and when the user submits this form, all we need to do is hit the logout action , which we will implement via the AccountController, and to disconnect the user.

    • If the user is not logged in and we have an anonymous user, then we need to show a link that will go to the AccountController, in particular to the login action, and it can display the text Login.

    • We also need to add a link for new users to register and go straight to the registration page.

    Now let's go to AccountController and first implement the disconnect action as in the following program.

    [HttpPost] public Task Logout () {await _signManager.SignOutAsync return RedirectToAction ( "Index ", "Home "); }

    • This action only responds to HttpPost. It 's a hrone action. We will need to call another hrone method on the Identity framework.

    • We can return a task from IActionResult and the action is named Logout.

    • All we need to do to log out is wait for the SignOutAsync method of SignInManager .

    • User context has changed now; we now have an anonymous user. The view will be redirected to the home page and we will return to the employee list.

    Now let's move on and build our login function. Here we will need a pair of actions, one that responds to an HttpGet request and displays the form we can use to login, and one that responds to an HttpPost request.

    To begin with, we will need a new ViewModel to extract the connection data because the connection is very different from the recording. So, let's add a new class and call it LoginViewModel .

    public class LoginViewModel {public string Username {get; together; } [DataType (DataType.Password)] public string Password {get; together; } [Display (Name = "Remember Me ")] public bool RememberMe {get; together; } public string ReturnUrl {get; together; }}

    • When users log in, they must provide information such as username, password.

    • The third piece of information should be the login user interfaces. These are accompanied by ae little checkbox that says "Do you want to remember me". This is the choice between do we want a session cookie or do we want a more permanent cookie.

    • To enable this functionality, we added a Boolean RememberMe property and we used a Display annotation. Now when we build a label, the text Remember Me is displayed with a space.

    • The last information we actually want as part of this ViewModel is to have a property that will store ReturnUrl.

    Now let's add the login action that will respond to the Get request as shown in the following program.

    [HttpGet] public IActionResult Login (string returnUrl = "") {var model = new LoginViewModel {ReturnUrl = returnUrl}; back View (model); }

    • We will take returnUrl as a parameter which isfound in the query string.

    • The returnUrl may not always be there. Leave us an empty string as the default.

    We will now have a new view by adding a new MVC view page in the Views → Account folder.

     ASP.NET Core - Quick Guide

    In the central pane, select the MVC display page and name it Login.cshtml, then click the Add button. Let's add the following code to the Login.cshtml file.

    @model LoginViewModel @ {ViewBag.Title = " Login}

    Login

    • In this login view, we set the page title to Login, then we have a form that will be able tolinked to the AccountLogin action.

    • We need to use a tag helper, asp-route-returnurl , to make sure ReturnUrl is there in the URL where the form returns.

    • We need to send this ReturnUrl back to the server so that if the user connects successfully, we can send it to where it was trying to go .

    • Anything you add after asp-route-, id or returnurl, whatever you have there, that will go somewhere in the request, either in the path of the 'URL, or as a query string parameter.

    • We have our ValidationSummary and the entries for Username, Password and RememberMe, then we have a Submit button.

    ` AccountController , a nd implement the Post action. This action that responds to HttpPost. It will be an Async method because we will need to call the Identity framework and return une task or IActionResult.

    [HttpPost] public Task Login (LoginViewModel model) {if (ModelState.IsValid) {var result = wait _signManager.PasswordSignInAsync (model.Username, model. Password, model.RememberMe, false); if (result.Succeeded) {if (! string.IsNullOrEmpty (model.ReturnUrl) && Url.IsLocalUrl (model.ReturnUrl)) {return Redirect (model.ReturnUrl); } else {return RedirectToAction ( "Index ", "Home "); }}} ModelState.AddModelError ( "", "Invalid connection attempt "); back View (model); }

    • We call this login, and now we hope to receive a LoginViewModel.

    • We need to check if ModelState is valid. If valid, connect to the user by calling an API on the SignInManager.

    • The PasswordSignInAsync method will return a result and if the result is successful we know the user has logged inwith success.

    • We also have a return url. If this is a valid local url, we will be redirected to the return url.

    • If the user has just logged in and does not have a specific place to go, we will redirect the user to the action HomeController index.

    • We could be in a situation where the user provides an invalid password or an invalid username. We also need to add a template error that asks if there is an invalid login attempt. It helps the user to know if something is wrong.

    Now let's save everything and run the application.

     ASP.NET Core - Quick Guide

    We now have connection and inion links. Let's click on the connection link.

     ASP.NET Core - Quick Guide

    Let's connect with the 'user that we created in the previous chapter by specifying Username and Password and check the box Remember me .

    When you click on the Connect button, the browser asks if you want to save your password for the local host. Let's click on the Yes button.

    ASP.NET Core Quick Guide

    Now we log out by clicking the Logout button.

     ASP.NET Core Quick Guide

    As 'anonymous user, let's try to edit employee details.

     ASP .NET Core Quick Guide

    You can now see that we have been redirected to the login view .

    Let us login with your username and password and check the Remember Me checkbox.

     ASP.NET Core - Quick Guide

    Now , click the Connection button.

    ASP.NET Core - Guide quick

    You can now see that we are directed to the URL we want to change. Indeed, we have handled the return URL appropriately .