ASP.NET Core

本篇已收录至 asp.net core 随笔系列

Reference

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/startup?view=aspnetcore-2.2

谈谈 startup 作用

  • 可以在 startup 中配置(注册) app 所需要的 service.
  • 定义 http 请求的 pipeline. 比如指定使用的静态文件, 默认路由等等.

Startup示例

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

        services.AddDbContext<MovieContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("MovieDb")));
    }

    public void Configure(IApplicationBuilder app)
    {
        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseMvc();
    }
}

DI示例 : 在其他的文件中使用Startup中注册的 EF core 的 DBContext, 通过构造函数传参的形式, 将注册的 service 注入到 IndexModel 当中

public class IndexModel : PageModel
{
    private readonly MovieContext _context;

    public IndexModel(MovieContext context)
    {
        _context = context;
    }
    // ...
    public async Task OnGetAsync()
    {
        var movies = from m in _context.Movies
                        select m;
        Movies = await movies.ToListAsync();
    }
}

Http 请求管道(即 request pipeline)实际上是一系列的中间件, 每个中间件会对 HttpContext 进行一些特定的异步的处理或者响应这个 HttpContext

public void ConfigureStaging(IApplicationBuilder app, IHostingEnvironment env)
{
    if (!env.IsStaging())
    {
        throw new Exception("Not staging.");
    }

    app.UseExceptionHandler("/Error");
    app.UseStaticFiles();
    app.UseMvc();
}
原文地址:https://www.cnblogs.com/it-dennis/p/12626071.html