الأحد، 2 سبتمبر 2018

ASP.NET Core 2.0 MVC Your First Application

سبتمبر 02, 2018




1. Your First ASP.NET Core Application



If you haven’t already installed Visual Studio 2017 version 15.3.5 version or later, you can download a free copy here: www.visualstudio.com/downloads.

Now that you have Visual Studio 2017 installed on your computer, it’s time to create your first solution and project.

    Open Visual Studio 2017 and select File-New-Project in the main menu to create a new solution.

    Click on the Web tab and then select ASP.NET Core Web Application in the template list (see image below).

    Name the project AspNetCoreVideo in the Name field.

    Select a folder for the solution in the Location field.

    Name the solution AspNetVideoCore in the Solution name field.

    Make sure that the Create directory for solution checkbox is checked.

    Learning how to use GitHub is not part of this course, so if you are unfamiliar with GitHub, you should make sure that the Create new Git repository checkbox is unchecked.

    Click the OK button.

    In the project template dialog:

    Select.NET Core and ASP.NET Core 2.0 in the two drop-downs.

    Select Empty in the template list.

    Click the OK button in the wizard dialog.

    When the solution has been created in the folder you selected, it will contain all the files in the AspNetVideoCore project.

    Press Ctrl+F5 on the keyboard, or select Debug-Start Without Debugging in the main menu, to run the application in the browser.

    Note that the application only can do one thing right now, and that is to display the text Hello World! Later in this, and the next, module you will learn why that is, and how you can change that behavior.










9

ASP.NET Core 2.0 MVC & Razor Pages for Beginners



















































For now, just note that the application is running on localhost:55554 (the port number might be different on your machine).




10

ASP.NET Core 2.0 MVC & Razor Pages for Beginners

















If you right click on the IIS icon in the system tray, you can see that ISS is hosting the AspNetCoreVideo application.



















The Project Layout and the File System

There is a direct correlation between the files in the solution folder and what is displayed in the Solution Explorer in Visual Studio. To demonstrate this, you will add a file to the file structure in the File Explorer and see it show up in the Solution Explorer in real-time.

    Right click on the AspNetVideoCore solution node in the Solution Explorer and select Open Folder in File Explorer.

    When the File Explorer has opened, you can see that the solution file AspNetCoreVideo.sln is in that folder, along with the project folder with the same name.

    Double click on the project folder in the File Explorer to open it.



11

ASP.NET Core 2.0 MVC & Razor Pages for Beginners


    Right click in the File Explorer window and select New-Text Document and press Enter on the keyboard.

    A new file with the name New Text File should have been created in the folder.

    Now look in the Solution Explorer in Visual Studio; the same file should be available there.

    Double click the icon for the New Text File document in the Solution Explorer in Visual Studio, to open it.

    Write the text Some text from Visual Studio in the document and save it.

    Now switch back to the File Explorer and open the file. It should contain the text you added.

    Change the text to Some text from Notepad using the text editor (not in Visual Studio) and save the file.

    Switch back to Visual Studio and click the Yes button in the dialog. The altered text should now be displayed in Visual Studio.















    Close the text document in Visual Studio and in the text editor.

    Right click on the file in the Solution Explorer in Visual Studio and select Delete to remove the file permanently.

    Go to the File Explorer and verify that the file was deleted from the folder structure.

As you can see, the files in the project are in sync with the files in the file system, in real-time.

Important Files

There are a couple of files that you need to be aware of in ASP.NET Core 2.0, and these have changed from the 1.0 version.




12

ASP.NET Core 2.0 MVC & Razor Pages for Beginners


The Properties folder in the Solution Explorer contains a file called launchSettings.json, which contains all the settings needed to launch the application. It contains IIS settings, as well as project settings, such as environment variables and the application URL.

One major change from ASP.NET Core 1.0 is that the project.json file no longer exists; instead the installed NuGet packages are listed in the .csproj file. It can be opened and edited directly from Visual Studio (which is another change) or its content can be changed using the NuGet Package Manager.

To open the .csproj file, you simply right click on the project node in the Solution Explorer and select Edit AspNetVideoCore.csproj (substitute AspNetVideoCore with the name of the project you are in).

You can add NuGet packages by adding PackageReference nodes to the file .csproj, or by opening the NuGet Package Manager. Right click on the project node or the References node, and select Manage NuGet Packages to open the NuGet Manager.

One change from the ASP.NET Core 1.1 version is that there now only is one main NuGet package called Microsoft.AspNetCore.All that is installed when the project is created. It contains references to the most frequently used NuGet packages, the ones that you had to add separately in the 1.1 version.

Open the .csproj file and the NuGet manager side by side and compare them. As you can see, the same package is listed in the dialog and in the file.

























13

ASP.NET Core 2.0 MVC & Razor Pages for Beginners











You will be adding more NuGet packages (frameworks) as you build the projects.

Compiling the Solution

It is important to know that ASP.NET will monitor the file system and recompile the appli-cation when files are changed and saved. Because ASP.NET monitors the file system and recompiles the code, you can use any text editor you like, such as Visual Studio Code, when building your applications. You are no longer bound to Visual Studio; all you need to do is to get the application running in the web server (IIS). Let’s illustrate it with an example.

    Start the application without debugging (Ctrl+F5) to get it running in IIS, if it isn’t already open in a browser.

    Open the Startup.cs file with Notepad (or any text editor) outside of Visual Studio. This file is responsible for configuring your application when it starts.

    Locate the line of code with the string Hello World. This line of code is responsible for responding to every HTTP request in your application. await context.Response.WriteAsync("Hello World!");

    Change the text to Hello, from My World! and save the file.

await context.Response.WriteAsync("Hello, from My World!");

    Refresh the application in the browser. Do not build the solution in Visual Studio before refreshing the page.

    The text should change from Hello World! To Hello, from My World! The reason this works is because ASP.NET monitors the file system and recompiles the application when changes are made to a file.














14

ASP.NET Core 2.0 MVC & Razor Pages for Beginners


You can create cross-platform applications using ASP.NET Core 2.0, but this requires the

.NET Core template. As of this writing, this template has limitations compared with the .NET Framework template. This is because .NET Framework contains features that are relying on the Windows operating system. In a few years’ time, this gap will probably not be as significant, as the .NET Core platform evolves. So, if you don’t need the added features in .NET Framework, then use the .NET Core template, as it is much leaner and cross-platform ready.

The Startup.cs File

Gone are the days when the web.config file ruled the configuration universe. Now the Startup.cs file contains a Startup class, which ASP.NET will look for by convention. The application and its configuration sources are configured in that class.

The Configure and ConfigureServices methods in the Startup class handle most of the application configuration. The HTTP processing pipeline is created in the Configure method, located at the end of the class. The pipeline defines how the application responds to requests; by default, the only thing it can do is to print Hello World! to the browser.

If you want to change this behavior, you will have to add additional code to the pipeline in this method. If you for instance want to handle route requests in an ASP.NET MVC appli-cation, you have to modify the pipeline.

In the Configure method, you set up the HTTP request pipeline (the middleware) that is called when the application starts. In the second part of this book, you will add an object-to-object mapper called AutoMapper to this method. AutoMapper transforms objects from one type to another.

The ConfigureServices method is where you set up the services, such as MVC. You can also register your own services and make them ready for Dependency Injection (DI); for instance, the service that you implement using the IMessageService interface at the beginning of the book.

You will learn more about how to configure your application in the next chapter.

For now, all you need to know about dependency injection is that, instead of creating in-stances of a class explicitly, they can be handed to a component when asked for. This makes your application loosely coupled and flexible.






15

ASP.NET Core 2.0 MVC & Razor Pages for Beginners


Adding a Configuration Service

Let’s say that the hard-coded string Hello, from My World is a string that shouldn’t be hardcoded, and you want to read it from a configuration source. The source is irrelevant; it could be a JSON file, a database, a web service, or some other source. To solve this, you could implement a configuration service that fetches the value when asked.

Let’s implement this scenario in your application

    Right click on the project folder and select Add-New Item.

    Search for JSON in the dialog’s search field.

    Select the ASP.NET Configuration File template.

    Make sure the name of the file is appsettings.json. The file could be named anything, but appsettings is convention for this type of configuration file.

    Click the Add button.

    As you can see, a default connection string is already in the file. Remove the connection string property and add the following key-value pair:

“Message”:”Hello, from configuration”. This is the file content after you have changed it.

{
"Message": "Hello, from configuration"

}

    To read configuration information from the appsettings.json file, you have to add a constructor to the Startup class. You can do that by typing ctor and hitting the Tab key twice in the class.

public class Startup
{

public Startup()
{

}
...

}

    You need to create an instance of the ConfigurationBuilder class called builder in the constructor, and chain on the SetBasePath method with the application’s current directory as an argument. Without specifying the base path, the application will not know where to search for files.

var builder = new ConfigurationBuilder()

.SetBasePath(Directory.GetCurrentDirectory());




16

ASP.NET Core 2.0 MVC & Razor Pages for Beginners


    To get access to the classes used in the previous step, you have to resolve the following two namespaces by adding using statements for them.

using Microsoft.Extensions.Configuration; using System.IO;

    To read the JSON appsettings.json file you need to chain on the AddJsonFile method, with appsettings.json as an argument, to the builder object. If you need to include more files, you can chain on the method multiple times.

var builder = new ConfigurationBuilder()

.SetBasePath(Directory.GetCurrentDirectory())

.AddJsonFile("appsettings.json");

    Add a property called Configuration, of type IConfiguration, to the Startup class. public IConfiguration Configuration { get; set; }

    Now, you need to build the configuration structure from the ConfigurationBuilder object, and store it in the Configuration property. You do this by calling the Build method on the builder variable in the constructor.

Configuration = builder.Build();

    To replace the hardcoded text Hello, from My World! with the value stored in the Message property in the appsettings.json file, you have to index into the Configuration property. Store the value in a variable in the Configure method above the WriteAsync method call.

var message = Configuration["Message"];

    Now, replace the hardcoded text with the variable. await context.Response.WriteAsync(message);

    Save all the files and go to the browser. Refresh the application to see the new message.



















17

ASP.NET Core 2.0 MVC & Razor Pages for Beginners


The Startup class’s code, so far:

public class Startup

{
public IConfiguration Configuration { get; set; }

public Startup()
{

var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())

.AddJsonFile("appsettings.json"); ;

Configuration = builder.Build();

}

public void ConfigureServices(IServiceCollection services)
{

}

public void Configure(IApplicationBuilder app, IHostingEnvironment env) {

if (env.IsDevelopment())
{

app.UseDeveloperExceptionPage();
}

app.Run(async (context) =>
{

var message = Configuration["Message"]; await context.Response.WriteAsync(message);

});
}

}

Creating a Service

Instead of using one specific source to fetch data, you can use services to fetch data from different sources, depending on the circumstance. This mean that you, through the use of configuration, can use different data sources according to the need at hand.

You might want to fetch data from a JSON file when building the service, and later switch to another implementation of that service, to fetch real data.




18

ASP.NET Core 2.0 MVC & Razor Pages for Beginners


To achieve this, you create an interface that the service classes implement, and then use that interface when serving up the instances. Because the service classes implement the same interface, instances from them are interchangeable.

To get access to the services from the Configure method in the Startup class, or any other constructor, model, Razor Page, or view, you must use dependency injection. That is, pass in the interface as a parameter to the method.

You must register the service interface, and the desired service class, with the services collection in the ConfigureServices method, in the Startup class. This determines which class will be used to create the instance, when dependency injection is used to pass in an instance of a class implementing the interface.

In the upcoming example, you will inject a service class into the Configure method, but it works just as well with regular classes that you want to inject into a constructor, model, Razor Page, or view, using dependency injection. The same type of registration that you did in the ConfigureServices method could be applied to this scenario, but you wouldn’t have to implement it as a service.

You might ask how the IApplicationBuilder parameter gets populated in the Configure method, when no configuration has been added for it in the ConfigureServices method. The answer is that certain service objects will be served up for interfaces automatically by ASP.NET; one of those interfaces is the IApplicationBuilder. Another is the IHosting-Environment service, which handles different environments, such as development, staging, and production.

Example

Let’s implement an example where you create two service classes that retrieve data in two different ways. The first will simply return a hardcoded string (you can pretend that the data is fetched from a database or a web service if you like), and the second class will return the value from the Message property that you added to the appsettings.json file.

You will begin by adding an interface called IMessageService, which will define a method called GetMessage, which returns a string.

Then you will implement that interface in a service class called HardcodedMessage-Service, which will return a hardcoded string. After implementing the class, you will add configuration for it and the interface in the ConfigureServices method and test the functionality.



19

ASP.NET Core 2.0 MVC & Razor Pages for Beginners


Then you will implement another class called ConfigurationMessageService, which reads from the application.json file and returns the value from its Message property. To use the new service class, you must change the configuration. Then you will refresh the application in the browser to make sure that the configuration value is returned.

Adding the IMessageService Interface

    Right click on the project node in the Solution Explorer and select Add-New Folder.

    Name the folder Services.

    Right click on the Services folder and select Add-New Item.

    Select the Interface template, name the interface IMessageService, and click the Add button.

    Add the public access modifier to the interface (make it public).

    Add a method called GetMessage, which returns a string to the interface. It should not take any parameters.

    Save the file.

The complete code for the interface:

public interface IMessageService
{

string GetMessage();

}

Adding the HardcodedMessageService Class

    Right click on the Services folder and select Add-Class.

    Name the class HardcodedMessageService and click the Add button.

    Implement the IMessageService interface in the class by clicking on the light bulb icon that appears when you hover over the interface name when you have added it to the class. Select Implement interface in the menu that appears.

    Remove the code line with the throw statement and return the string Hardcoded message from a service.

    Save all files by pressing Ctrl+Shift+S on the keyboard.










ads2
رسالة أحدث
Previous
This is the last post.

0 التعليقات:

إرسال تعليق

 
Toggle Footer