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

ASP.NET Core 2.0系列学习笔记-启动类Startup

2018-02-26 23:00 1626 查看
Startup类可以用来定义处理管道和配置应用需要的服务。Startup类必须是public修饰,并且包含如下方法:public class Startup
{
// 运行时调用此方法。使用此方法向容器添加服务。
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
//使用此方法向容器添加服务。
}

// 运行时调用此方法。使用此方法配置HTTP请求管道。
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
//使用此方法配置HTTP请求管道中间件。
}
}ASP.NET Core 2.0 MVC 默认Startup类如下:using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace NETCoreMVC
{
public class Startup
{    //构造函数,加载配置文件
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

public IConfiguration Configuration { get; } //配置文件实体

// 运行时调用此方法。使用此方法向容器添加服务。
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(); //添加MVC服务
}

// 运行时调用此方法。使用此方法配置HTTP请求管道。(Requsert请求管道)
// 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.UseBrowserLink();
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}

app.UseStaticFiles(); //使用wwwroot静态文件

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

}
总结:
1. ConfigureServices方法用于定义(注册)应用程序所使用的服务。(如:ASP.NET Core MVC,Entity Framework Core,Identity 等);
2. Configure方法用于定义请求管道的中间件,该管道将用于处理应用程序的所有请求。
3. 注册服务添加方法是无序的,ASP.NET Core在应用程序启动的时候,只要有相应服务即可,而注册中间件时方法是有序的,管道内的每一个组件都可以选择是否将请求交给下一个组件,并在管道中调用下一个组件之前或之后执行某些操作。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息