把舊系統遷移到.Net Core 2.0 日記(1) - Startup.cs 解析


因為自己到開發電腦轉到Mac Air,之前的Webform/MVC應用在Mac 跑不起來,而且.Net Core 2.0 已經比較穩定了。

1. 為什么會有跨平台的.Net Core 

近年來,我們已經進入雲計算時代,在雲平台的PaSS和SaSS上也是發生了大幅度的進化,以docker為代表。微軟的Azure平台,google的GAE等等各大雲計算廠商都提供了PaSS平台,我們的應用程序要遷移到這樣的平台上都需要進行重寫。Docker,給雲計算帶來一場革新,Docker可以被認為是互聯網的集裝箱,可以靈活地封裝軟件,令其更快速地傳播。這對現代互聯網來說是一件大事,因為軟件都會運行上成百上千的機器上。Docker可以改變我們開發軟件的方式,令每個人都能便捷地利用大量的運算能力。Docker可以讓開發者專注於開發軟件,不需要考慮在哪里運行自己的軟件,這才是雲計算的發展方向。開發者考慮應用本身就足夠了。

以往的.NET 很難進入以docker為代表的雲計算開發平台,特別是Windows不支持Docker,因為那完全是互聯網服務的基石--Linux系統才有的技術,微軟為了適應這樣的雲計算潮流,在Windows Server 2016/Windows 10上支持了docker,也重新開發跨平台.NET Core的應用運行平台。

2. 對Old .Neter, 如何盡快熟悉.Net Core 呢?

我們在vs.net 新建一個Empty Core solution, 看看程序入口program.cs,它還是一個console程序. 多引入了4個命名空間. ASP.NET Core應用的寄宿依賴於一個WebHost對象,通過對應的CreateDefaultBuilder的工廠方法創建啟動一個WebHost, web服務器. 注冊調用了StartUp類. 這個類里面會注冊一些中間件.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace sso
{
    public class Program
    {
        public static void Main(string[] args)
        {
            BuildWebHost(args).Run();
        }

        public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
                .Build();
    }
}

Startup類里有configureServices和configure方法, 調用順序是先ConfigureServices后Configure。

這2個的區別是: 其中和Dependecy Injection有關的方法是放在ConfigureServices()中,

Configure()是和Middleware相關的方法

    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("Hello World!");
            });
        }
    }

默認Empty的solution是只有一個Hello World,我們看一下典型的數據庫應用,這個文件會是怎么樣的,引入EF,MVC等中間件

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

    services.AddIdentity<ApplicationUser, IdentityRole>()
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultTokenProviders();

    services.AddMvc();

    // Add application services.
    services.AddTransient<IEmailSender, AuthMessageSender>();
    services.AddTransient<ISmsSender, AuthMessageSender>();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseBrowserLink();
    }
    else
    {
        app.UseExceptionHandler("/Error");
    }

    app.UseStaticFiles();

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller}/{action=Index}/{id?}");
    });
}

如果要引入其他中間件,比如這個,可以參考下面文章.

ASP.NET Core 中間件之壓縮、緩存
asp.net core 2.0 查缺補漏
中間件配置主要是用RunMapUse方法進行配置,請參考這個文章  ASP.NET Core 運行原理剖析

 犯了一個錯誤,在 https://docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?tabs=aspnetcore2x  這里有提到

Don't call next.Invoke after the response has been sent to the client. Changes to HttpResponse after the response has started will throw an exception.

錯誤代碼如下: 這個代碼運行時會出錯,錯誤是

該網頁無法正常運作

localhost 意外終止了連接。

ERR_INCOMPLETE_CHUNKED_ENCODING
            app.Use(async (context,next) =>
            {
                context.Response.WriteAsync("Hello World!"); await next();
            });
            app.Run(async (context)=>
            {
                await context.Response.WriteAsync("NET Core!");
            });
 就是說你在中間件里用了Response.Write就不能用Next, 或者說Response.Write 只能用在最后的Use里.

 

把舊系統遷移到.Net Core 2.0 日記 (15) --Session 改用Redis
 把舊系統遷移到.Net Core 2.0 日記 (13) --圖形驗證碼
把舊系統遷移到.Net Core 2.0 日記 (12) --發布遇到的問題
把舊系統遷移到.Net Core 2.0 日記(11) -- Authentication 認證 claimsIdentity 對比 之前的FormAuthentication
把舊系統遷移到.Net Core 2.0 日記(10) -- EF core 和之前版本多對多映射區別
把舊系統遷移到.Net Core 2.0 日記(9) -- T4 Template
把舊系統遷移到.Net Core 2.0 日記(8) - EASYUI datagrid
把舊系統遷移到.Net Core 2.0 日記(7) Tag Helpers /ResponseCache
把舊系統遷移到.Net Core 2.0 日記(6) MapRoute/Area/ViewPath
把舊系統遷移到.Net Core 2.0 日記(5) Razor/HtmlHelper/資源文件
把舊系統遷移到.Net Core 2.0 日記(4) - 使用EF+Mysql
把舊系統遷移到.Net Core 2.0 日記(3) - 詳解依賴注入
把舊系統遷移到.Net Core 2.0 日記(2) - 依賴注入/日志NLog

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM