ASP.NET Core 3.1 Startup类

简介

Startup 类包含一个可选的ConfigureServices方法,用来配置应用的服务。还包含一个Configure方法,来创建程序的请求处理管线。

当使用IHostBuilder时,只有以下三个服务能够注入Startup类的构造函数

  • IWebHostEnvironment
  • IHostEnvironment
  • IConfiguration
    大部分服务直到调用Configure方法后才能使用。

ConfigureService方法

  • 可选
  • 在Configure方法配置程序的服务之前由host调用
  • 通常设置服务的选项 options
    经常使用的服务IServiceCollection 有Add护展方法,例如AddDbContext, AddDefaultIdentity, AddEntityFrameworkStores, 和AddRazorPages。
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();
    }

将服务添加到容器后,程序和Configure方法就可以使用。服务通过DI或IApplicationBuilder的ApplicationServices来调用。

Configure方法

Configure方法指定程序如何响应Http请求。请求处理管线通过向IApplicationBuilder实例添加中间件来配置,IApplicationBuilder没有注册到IOC容器,Hosting创建一个IApplicationBuilder 直接传给Configure方法。

用过滤器扩展Startup

 public class RequestSetOptionsStartupFilter : IStartupFilter
    {
        public Action<IApplicationBuilder> Configure(Action<IApplicationBuilder> next)
        {
            return builder =>
            {
                builder.UseMiddleware<RequestSetOptionsMiddleware>();
                next(builder);
            };
        }

    }
    public class RequestSetOptionsMiddleware
    {
        private readonly RequestDelegate _next;
        public RequestSetOptionsMiddleware(RequestDelegate next)
        {
            _next = next;
                
        }
        public async Task Invoke(HttpContext httpContext)
        {
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            var option = httpContext.Request.Query["option"];
            if (!string.IsNullOrWhiteSpace(option))
            {
                httpContext.Items["option"] = WebUtility.HtmlEncode(option)+444;
            }
            await _next(httpContext);
            stopwatch.Stop();
            Console.WriteLine("请求用时ms:"+stopwatch.ElapsedMilliseconds);
        }

    }

ConfigureServices中添加

services.AddTransient<IStartupFilter, MiddleWares.RequestSetOptionsStartupFilter>();
        
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值