ASP.NET Core 基础知识之​Startup 类配置

简介: Startup 类配置服务和应用的请求管道。

Startup 类配置服务和应用的请求管道。


ASP.NET Core 应用使用 Startup 类,按照约定命名为 Startup。 Startup 类:


1.可选择性地包括 ConfigureServices 方法以配置应用的服务 。 服务是一个提供应用功的可重用组件。 在 ConfigureServices 中注册服务,并通过依赖关系注(DI) 或 Application-Services 在整个应用中使用服务 。


2.包括 Configure 方法以创建应用的请求处理管道。



在应用启动时,ASP.NET Core 运行时会调用 ConfigureServices 和 Configure:


方法调用顺序: Main -> ConfigureServices -> Configure

 public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
        public IConfiguration Configuration { get; }
        //在 ConfigureServices 中注册服务,并通过依赖关系注入 (DI) 或 ApplicationServices 在整个应用中使用服务
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }
        // Configure 方法用以创建应用的请求处理管道。
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseMvc();
        }


ConfigureServices 方法:


ConfigureServices 方法:


1.可选。


2.在 Configure方法配置应用服务之前,由主机调用。


3.其中按常规设置配置选项。



对于需要大量设置的功能,IServiceCollection 上有 Add{Service} 扩展方法。 例如,AddDbContext、AddDefaultIdentity、AddEntityFrameworkStores 和 AddRazorPages等方法:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }
    public IConfiguration Configuration { get; }
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(
                Configuration.GetConnectionString("DefaultConnection")));
        services.AddDefaultIdentity<IdentityUser>(
            options => options.SignIn.RequireConfirmedAccount = true)
            .AddEntityFrameworkStores<ApplicationDbContext>();
        services.AddRazorPages();
    }
}


执行到Startup的时候,IConfiguration已经被注入到services了,不需要我们额外添加注入

的代码,但是缺少读取appsettings.json文件,你可以理解在Startup.cs里有隐藏的注入代码

类似如下:

var builder = new ConfigurationBuilder()
               .SetBasePath(env.ContentRootPath)
               .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
               .AddEnvironmentVariables();
Configuration = builder.Build();
services.AddSingleton<IConfiguration>(Configuration);


我们可以使用

使用IOptions,获取appsetting.json配置文件中的值

例如:appsetting.json中数据为:

{
  "key1": "KeyVule1",
  "key2": "KeyVule2"
}


创建appsetting.json对应的类:

public class appModel
    {
        public string key1 { get; set; }
        public string key2 { get; set; }
    }

2.在 ConfigureServices中注册相应的服务:

services.Configure<appModel>(Configuration);

3.在你想要使用的控制器的构造函数中传递参数:

  [Route("api/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        public IOptions<appModel> _options;
        public ValuesController(IOptions<appModel> options)
        {
            _options = options;
        }
        // GET api/values
        [HttpGet]
        public ActionResult<IEnumerable<string>> Get()
        {
            return new string[] { _options.Value.key1, _options.Value.key2 };
        }
    }


Configure 方法


Configure 方法用于指定应用响应 HTTP 请求的方式。 可通过将中间件组件添加到 IApplicationBuilder 实例来配置请求管道。 Configure 方法可使用 IApplicationBuilder,但未在服务容器中注册。 托管创建 IApplicationBuilder 并将其直接传递到 Configure。


ASP.NET Core 模板配置的管道支持:


开发人员异常页


异常处理程序


HTTP 严格传输安全性 (HSTS)


HTTPS 重定向


静态文件


ASP.NET Core MVC 和 Razor Pages

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }
    public IConfiguration Configuration { get; }
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddRazorPages();
    }
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            app.UseHsts();
        }
        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseRouting();
        app.UseAuthorization();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapRazorPages();
        });
    }
}

每个 Use 扩展方法将一个或多个中间件组件添加到请求管道。例如,UseStaticFiles 配置中间件提供静态文件。


请求管道中的每个中间件组件负责调用管道中的下一个组件,或在适当情况下使链发生短路。


可以在 Configure 方法签名中指定其他服务,如 IWebHostEnvironment、ILoggerFactory 或 ConfigureServices


中定义的任何内容。如果这些服务可用,则会被注入。

目录
相关文章
|
19天前
|
数据可视化 网络协议 C#
C#/.NET/.NET Core优秀项目和框架2024年3月简报
公众号每月定期推广和分享的C#/.NET/.NET Core优秀项目和框架(每周至少会推荐两个优秀的项目和框架当然节假日除外),公众号推文中有项目和框架的介绍、功能特点、使用方式以及部分功能截图等(打不开或者打开GitHub很慢的同学可以优先查看公众号推文,文末一定会附带项目和框架源码地址)。注意:排名不分先后,都是十分优秀的开源项目和框架,每周定期更新分享(欢迎关注公众号:追逐时光者,第一时间获取每周精选分享资讯🔔)。
|
3月前
|
开发框架 前端开发 JavaScript
盘点72个ASP.NET Core源码Net爱好者不容错过
盘点72个ASP.NET Core源码Net爱好者不容错过
72 0
|
3月前
|
开发框架 .NET
ASP.NET Core NET7 增加session的方法
ASP.NET Core NET7 增加session的方法
37 0
|
3月前
|
开发框架 JavaScript .NET
ASP.NET Core的超级大BUG
ASP.NET Core的超级大BUG
43 0
|
3月前
|
开发框架 前端开发 .NET
ASP.NET CORE 3.1 MVC“指定的网络名不再可用\企图在不存在的网络连接上进行操作”的问题解决过程
ASP.NET CORE 3.1 MVC“指定的网络名不再可用\企图在不存在的网络连接上进行操作”的问题解决过程
43 0
|
1月前
|
开发框架 人工智能 .NET
C#/.NET/.NET Core拾遗补漏合集(持续更新)
C#/.NET/.NET Core拾遗补漏合集(持续更新)
|
1月前
|
开发框架 中间件 .NET
C# .NET面试系列七:ASP.NET Core
## 第一部分:ASP.NET Core #### 1. 如何在 controller 中注入 service? 在.NET中,在ASP.NET Core应用程序中的Controller中注入服务通常使用<u>依赖注入(Dependency Injection)</u>来实现。以下是一些步骤,说明如何在Controller中注入服务: 1、创建服务 首先,确保你已经在应用程序中注册了服务。这通常在Startup.cs文件的ConfigureServices方法中完成。例如: ```c# services.AddScoped<IMyService, MyService>(); //
65 0
|
2月前
|
开发框架 前端开发 .NET
福利来袭,.NET Core开发5大案例,30w字PDF文档大放送!!!
为了便于大家查找,特将之前开发的.Net Core相关的五大案例整理成文,共计440页,32w字,免费提供给大家,文章底部有PDF下载链接。
37 1
福利来袭,.NET Core开发5大案例,30w字PDF文档大放送!!!
|
2月前
|
算法 BI API
C#/.NET/.NET Core优秀项目和框架2024年1月简报
C#/.NET/.NET Core优秀项目和框架2024年1月简报
|
3月前
|
IDE 前端开发 JavaScript
【C#】C# 开发环境配置(Rider 一个.NET 跨平台集成开发环境)
【1月更文挑战第26天】【C#】C# 开发环境配置(Rider 一个.NET 跨平台集成开发环境)