您的位置:首页 > 编程语言 > ASP

ASP.NET CORE基础教程(一)-启动文件Startup

2017-04-29 22:46 1001 查看

ASP.NET CORE基础教程(一)-启动文件Startup

Startup类起到配置处理监听请求通道的作用。

Startup类

ASP.NET CORE应用程序必须有Startup文件,在主函数中调用,可以随意命名,但通常使用系统默认的startup.

可以通过startup的构造函数进行依赖注入。通过IHostingEnvironment、ILoggerFactory等加载各种配置或是日志等等。

startup类中必须包含Configure方法同时可以根据实际情况添加ConfigureServices方法,这两个方法均在应用程序运行时被调用。

Configure方法

该方法用于指出asp.net core应用程序如何响应HTTP请求。通过向IApplicationBuilder实例添加中间件组件来配置请求管道。

下面的例子中就包含了使应用程序支持错误页、静态文件、MVC、身份验证等等,

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();

if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}

app.UseStaticFiles();

app.UseIdentity();

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


通过使用usexxx方法来添加中间件到请求管道上,例如使用useMvc给应用程序添加MVC支持。更多的关于中间件的知识请看相关教程-中间件。

ConfigureServices方法

该方法不是必须的。如果使用的话,他必须在Configure之前。配置参数一般在这个方法里设置。

需要使用服务的话可以通过addxxx扩展方法来添加,一下例子使用了服务项,其中包括Entity Framework, Identity, 以及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>();
}


只有把服务添加到服务容器中才能让这些服务可以通过依赖注入的形式在应用中使用。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  asp.net asp-net-core