ASP.NET Core: What I learned!

ASP.NET Core is the latest web framework from Microsoft, and it's engineered to be fast, easy, and work cross platforms.

Internals of ASP.NET Core

One of the most important part of ASP.NET Core project is Startup.cs and what makes this class so special: ASP.NET Core instantiate this class and invoke two methods: one method which is ConfigureServices, this gives us the ability to put our own custom services into ASP.NET Core, and then have the services injected into pages, controllers and anywhere we need them. And then the other method ASP.NET Core will invoke on the Startup class is the Configure method. The Configure method is going to establish what middleware will execute for each incoming HTTP message.

1. aspnet-codegenerator

If we aren't using Visual Studio, the scaffolding shown in this clip is something you can also achieve with the dotnet-aspnet-codegenerator tool. The command would look like:

dotnet aspnet-codegenerator controller -api -name ControllerName -model ModelName --dataContext DataContext

2. Tag Helpers

Tag Helper helps up to render HTML on the server. Tag helpers that Microsoft provide out of the box start with asp-. Some of them are:

  • asp-page: tag helper changes the href on an anchor tag to point to a specific page in the system.
  • asp-for: is a way of saying this input is for the following property that bind on te model with [BindProperty] attribute.
  • asp-route: It's a dynamic tag helper. With another dash at the end of this tag helper and then include the name of the parameter that we want to pass along. So in other words, if you want to pass a search term parameter to some page, then you could say asp-route-name equals and then some value. And what asp-route could do is figure out how it can pass name to the other pages, knowing that it knows about that pages.
  • asp-items: asp-items takes an IEnumerable of SelectListIem for dropdownlist. A SelectListItem is an object that describes one of the options in a select, so it has two significant properties.
  • asp-validation-for: will do is look in the ModelState, see if there's any errors for property, and if so, display the associated error message for that particular error.
  • partial: Partial is a tag helper that appears as full element, and when we use the partial tag helper, there's a couple parameters in what looks like HTML attributes, which are name and model.
  • environment: looks like an HTML tag, but it is processed on the server, is look at the current operating environment and will only emit the HTML inside of here if a condition is met.

3. TempData Attribute

When ASP.NET Core sees the TempData attribute, it's going to go into the TempData structure and look for something with the key of Property Name, whatever this property name is. If it finds a value for that key in tempdata, it's going to take the value and assign it to this property assuming the types match. Example:

[TempData]
public string Message {get; set;}

4. Entity Framework

The Entity Framework provides some methods that use to describe the DbContext that application is going to use. And that would be the method AddDbContext in ConfigureServices method.

There's actually two of these here, AddDbContext and AddDbContextPool, which is new for this version of ASP.NET Core, and suggest using AddDbContextPool. This will pool your DbContexts in an attempt to reuse DbContexts that have been created while the application is alive, which can lead to better performance and scalability.

5. Database Migrations

To create migration with SQL Server database on start of the application the all migrations need to be executed so that, model entities and database objects are sync. This can be done in the Main method by passing IWebHost object.

private static void MigrationDatabase(IWebHost host)
{
    using(var scope = host.Services.CreateScope())
    {
        var db = scope.ServiceProvider.GetRequiredService<DbContext>();
    }

    db.Database.Migrate();
}

6. View Components

View Components are independent and autonomously go out and build whatever model is needed and render a piece of UI that can be placed into the layout view. In ASP.NET Core derived from a base class, which is the ViewComponent class.

One of the most important differences between ViewComponent and Razor page that, ViewComponent doesn't respond to HTTP request. It resides in Razor page or Partial View. To use the ViewComponent, you need to register it _ViewImports are tagHelpers.

7. Publishing Self-Contained App

To publish the application as Self-Contained, you need to specify self-contained option with RID (Runtime IDentifier). RID values are used to identify the target platforms where the application runs. They're used by .NET packages to represent platform-specific assets in NuGet packages. The following values are examples of RIDs: linux-64, ubuntu.18.04-x64, win10-x64, osx.10.13-x64.

dotnet publish -runtime ubuntu.18.04-x64 --self-contained false

8. Middleware

Middleware components are pieces of code, which are added to application's pipeline and have the job of handling each request and response.

The execution of middleware in the pipeline is determined by the order in which we have added middleware components from top to bottom in code. There are 4 methods exposed by IApplicationBuilder, which allow to write basic middleware components inline and how to control the order of that middleware on your pipeline.

  • Run: can be used if we're going to terminate the chain in middleware.
  • Use: gives the options of passing the request onto the next component in the chain of handling the request itself terminating the chain and returning a response.
  • Map: it matches the start of the request path against the string provided.
  • MapWhen: it allows to pass a predicate in its parameter and execute in the branch base on the result of that predicate.

ASP.NET Core comes with the following middleware components built in: authenticate, cors, routing, session, static files etc.

Also, both HttpModules and HttpHandler could be migrated to middleware.

9. Secret Manager

To configure our application, we put the configuration settings in appsettings.json. That's good, but it still isn't great because the file is also checked into source control and may expose very important ID or secrets.

A good way to do is to add these configurations with a secret manager tool. Right-click the project and select Manage User Secrets. This will also edit the file, but that file will only be available on this machine and will not be checked into source control. To add secret manager file by command line:

dotnet user-secrets init
dotnet user-secrets set "facebook.ClientId" "Your Facebook ClientID..."
原文地址:https://www.cnblogs.com/matt1985/p/13030611.html