ASP.NET Core框架學習

參考:html

官網文檔:ASP.NET Coreios

深刻探究ASP.NET Core Startup初始化web

蔣金楠:書籍《ASP.NET Core 3框架揭祕》、博客園 :ASP.NET Core 3框架揭祕 數據庫

梁桐銘:書籍《深刻淺出 ASP.NET Core》、 博客園:從零開始學 ASP.NET Core 與 EntityFramework Core 編程

ASP.NET Core跨平臺 技術內幕json

ASP.NET MVC從請求到響應發生了什麼bootstrap

ASP.NET/MVC/Core的HTTP請求流程windows

System.Configuration 命名空間 :包含提供用於處理配置數據的編程模型的類型api

  • Configuration 類 :表示適用於特定計算機、應用程序或資源的配置文件。 此類不能被繼承

啓動流程簡單說明

參考:瀏覽器

基礎知識

ASP.NET Core管道詳解[5]: ASP.NET Core應用是如何啓動的?[上篇]

ASP.NET Core管道詳解[6]: ASP.NET Core應用是如何啓動的?[下篇]

流程簡單說明以下:

  • 建立asp.net core項目後默認是一個應用臺控制程序,入口是Program類的Main方法
  • 在Main方法內調用了一個建立主機的方法CreateHostBuilder,此方法作了下面兩件事
    • CreateDefaultBuilder:建立通用主機
    • ConfigureWebHostDefaults:使用默認值配置IHostBuilder來託管Web應用程序,指定Startup類

Program類代碼以下:

    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }
        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }

 

以上是流程簡單說明,更詳細看下面的主機、託管、啓動類、配置等

主機

ASP.NET Core 應用在啓動時構建主機, 主機是封裝了應用的全部資源,例如:

  • HTTP 服務器實現
  • 中間件組件
  • 日誌
  • 依賴關係注入 (DI) 服務
  • 配置

 

有兩種主機,推薦使用通用主機

 

使用 Host.CreateDefaultBuilder (String[]) 方法建立通用主機

參考: CreateDefaultBuilder:使用預配置默認值初始化 HostBuilder 類的新實例

如下默認值將應用於返回的 HostBuilder :

反編譯查看CreateDefaultBuilder(String[])方法的源碼

// Microsoft.Extensions.Hosting.Host
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.EventLog;

public static IHostBuilder CreateDefaultBuilder(string[] args)
{
    HostBuilder hostBuilder = new HostBuilder();
    hostBuilder.UseContentRoot(Directory.GetCurrentDirectory());
    hostBuilder.ConfigureHostConfiguration(delegate(IConfigurationBuilder config)
    {
        config.AddEnvironmentVariables("DOTNET_");
        if (args != null)
        {
            config.AddCommandLine(args);
        }
    });
    hostBuilder.ConfigureAppConfiguration(delegate(HostBuilderContext hostingContext, IConfigurationBuilder config)
    {
        IHostEnvironment hostingEnvironment = hostingContext.HostingEnvironment;
        config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true).AddJsonFile("appsettings." + hostingEnvironment.EnvironmentName + ".json", optional: true, reloadOnChange: true);
        if (hostingEnvironment.IsDevelopment() && !string.IsNullOrEmpty(hostingEnvironment.ApplicationName))
        {
            Assembly assembly = Assembly.Load(new AssemblyName(hostingEnvironment.ApplicationName));
            if (assembly != null)
            {
                config.AddUserSecrets(assembly, optional: true);
            }
        }
        config.AddEnvironmentVariables();
        if (args != null)
        {
            config.AddCommandLine(args);
        }
    }).ConfigureLogging(delegate(HostBuilderContext hostingContext, ILoggingBuilder logging)
    {
        bool num = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
        if (num)
        {
            logging.AddFilter<EventLogLoggerProvider>((LogLevel level) => level >= LogLevel.Warning);
        }
        logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
        logging.AddConsole();
        logging.AddDebug();
        logging.AddEventSourceLogger();
        if (num)
        {
            logging.AddEventLog();
        }
    }).UseDefaultServiceProvider(delegate(HostBuilderContext context, ServiceProviderOptions options)
    {
        bool validateOnBuild = (options.ValidateScopes = context.HostingEnvironment.IsDevelopment());
        options.ValidateOnBuild = validateOnBuild;
    });
    return hostBuilder;
}
View Code 

託管Web應用程序

Host.ConfigureWebHostDefaults:使用默認值配置IHostBuilder來託管Web應用程序

如下默認值應用於IHostBuilder

  • 使用Kestrel做爲Web服務器,並使用應用程序的配置提供程序對其進行配置
  • WebRootFileProvider配置爲在開發過程當中包括入口程序集引用的項目中的靜態Web資產
  • 添加HostFiltering中間件
  • 若是ASPNETCORE_FORWARDEDHEADERS_ENABLED = true,則添加ForwardedHeaders中間件,
  • 啓用IIS集成
  • 經過 UseStartup 指定網絡主機要使用的啓動類型

啓動類Startup

啓動類中就是兩個方法,一個是依賴注入和服務註冊ConfigureServices,一個是中間件配置Configure

  • ConfigureServices (IServiceCollection services):依賴注入和服務註冊,例如數據庫上下文、控制器、其餘的依賴注入等
  • Configure (IApplicationBuilder app, IWebHostEnvironment env):用於指定應用響應 HTTP 請求的方式。 可經過將中間件組件添加到 IApplicationBuilder 實例來配置請求管道,例如路由、認證、跨越等

生成項目的Startup 類的代碼通常以下:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebRazor
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddRazorPages();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
            });
        }
    }
}
View Code

配置

概念

ASP.NET Core 中的配置是使用一個或多個配置提供程序執行的。 配置提供程序使用各類配置源從鍵值對讀取配置數據:

  • 設置文件,例如 appsettings.json
  • 環境變量
  • Azure Key Vault
  • Azure 應用程序配置
  • 命令行參數
  • 已安裝或已建立的自定義提供程序
  • 目錄文件
  • 內存中的 .NET 對象

 

讀取自定義的Json配置文件

參考:文件配置提供程序

在Program類的後面添加紅色的代碼,以下: 

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                })
 .ConfigureAppConfiguration((hostingContext, config) =>
                {
                    config.AddJsonFile("appsettings22.json", optional: true, reloadOnChange: true);
                });

 

模型驗證

參考:模型驗證

 

認證與受權

參考: 關於WEB Service&WCF&WebApi實現身份驗證之WebApi篇

認證

全局認證

參考:全局認證限制:必須登陸後才能訪問

單頁面SAP認證

使用 SPA 標識--.net core3.0起

使用identityserver4

受權

角色受權
策略受權

 

ASP.NET Core 中的Areas

 

ASP.NET Core MVC

工做原理:

啓動入口

Global.asax ==》Startup.cs

Global.asax 下面是一個MvcApplication類集成,該類繼承System.Web.HttpApplication,類下面是一個Application_Start方法,Application_Start方法中包含註冊區域、註冊全局的Filter、註冊路由、合併壓縮、打包工具Combres。

HttpApplication類定義對 ASP.NET 應用程序內全部應用程序對象公用的方法、屬性和事件。 此類是用戶在 Global.asax 文件中定義的應用程序的基類

簡單的流程

用戶請求是經過【視圖V】進入==》經過【控制器C】處理==》從【模型M】獲取數據==》最後返回給【視圖V】。

也知道ASP.NET MVC中的約定能夠經過修改配置來修改。

疑問

控制器、視圖、模型是怎麼根據約定來傳遞數據的

當時有一個疑問困惑很久,就是數據是怎麼經過控制器中發送到視圖的?

雖然知道能根據控制器內的方法來識別對應的視圖名稱,可是控制器方法的return是怎麼把模型數據發送到視圖的@model,當時記得本身折騰很久都沒整明白,百度搜索找到不多相關,最後看到《ASP.NET MVC 5框架揭祕》這本書才知道是和視圖引擎ViewEngine有關,視圖引擎會把控制器綁定的數據和視圖關聯起來

MVC中的http

修改約定

只搜索cshtml,默認會搜索多種視圖文件

在Global.asax中增長

/配置視圖搜索位置、文件類型,以提升性能

ViewEngines.Engines.Clear();

ViewEngines.Engines.Add(new CustomLocationViewEngine());

而後把CustomLocationViewEngine.cs文件放到App_Start

配置類/註冊類:

 Global.asax 下面類的方法內的註冊信息是怎麼被框架加載識別的?

ps:框架已經鎖定好MvcApplication、Application_Start的名稱的了,若是更更名稱就會報錯,也就是說只要在框架制定的方法中添加方法,框架在第一次啓動時會自動加載Application_Start內的方法。

部署到IIS

參考:使用 IIS 在 Windows 上託管 ASP.NET Core

安裝.net core託管捆綁包,下載對應版本:當前 .NET Core 託管捆綁包安裝程序(直接下載)

雙擊應用程序成,改成:無託管代碼

若是是64位的:鼠標右鍵=》設置應用程序池默認設置,啓用32位應用程序這裏要改成Lalse

標識設置爲有權限的帳號

Kestrel Web服務器

參考: 官方文檔Kestrel

http證書

要用dotnet run啓動項目

注意:此方法只是http能使用,並且須要網卡在使用的狀態(由於是),https仍是不能使用,還須要繼續深刻了解https

在項目文件下用命令(dotnet run)啓動時,大部分瀏覽器(IE不會)會報錯:ERR_HTTP2_INADEQUATE_TRANSPORT_SECURITY

端口要根據實際設置,能夠查看Properties文件夾下的文件launchSettings.json

Program類要添加下面紅色代碼,這裏只是端口的方式,還有更多方式(如TCPSocket、Limits等),能夠參考官方文檔,

或者參考官方教程的示例代碼,文件夾路徑:aspnetcore\fundamentals\servers\kestrel\samples\3.x\KestrelSample

端口若是不設置能夠用0,就是隨機端口

using System.Net; //要引用的命名空間

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>()
                    .ConfigureKestrel(serverOptions =>
                    {
                        serverOptions.Listen(IPAddress.Loopback, 5001); //端口爲0就是隨機端口 });
                });

 

而後項目文件的地址欄中輸入cmd進入命令窗口,而後經過命令啓動項目:dotnet run,注入,不能直接用vs啓動,不然仍是不能訪問

而後只能用紅色框內的地址訪問:http://127.0.0.1:5001/,(注意:用本機的https://localhost訪問仍是會失敗)

發佈後的生產環境

好像說須要安裝https證書,具體還要驗證。

不過按上面設置後,發佈後也能正常使用,安全問題???

視圖組件

參考:

官網文檔視圖組件

視圖組件封裝:.Net MVC&&datatables.js&&bootstrap作一個界面的CRUD有多簡單--鄒瓊俊

ConfigurationBuilder()
AddJsonFile
ConfigureWebHostDefaults
相關文章
相關標籤/搜索