1、前言
前面两篇博客主要介绍了依赖注入和控制反转的相关概念以及.NET Core
中内置IoC
容器的使用方法,给出的代码实例也都是基于控制台程序。从这篇博客开始,我们将创建WebAPI
应用程序进行演示。打开Visual Studio 2019
,选择ASP.NET Core Web API
,项目名称设置为App
,版本选择.NET Core 3.1
,工程创建完毕后如下图所示,解决方案资源管理器会显示如下图所示的内容,下面就来说一说这些文件的用处。
2、launchSettings.json
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:3607",
"sslPort": 44303
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "weatherforecast",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"App": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "weatherforecast",
"applicationUrl": "https://localhost:5001;http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
launchSettings.json
主要是在开发环境下的项目属性配置文件,如环境变量、开发端口等都可以在该文件中进行配置。重点来关注一下launchUrl
属性,该属性可配置程序启动时的默认URL
。新建一个控制器——HomeController
,如下图所示:
将HomeController
的路由属性设置为[Route("api/[controller]/[action]")]
,然后添加一个测试方法Get
,其代码如下所示:
using Microsoft.AspNetCore.Mvc;
namespace App.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class HomeController : ControllerBase
{
[HttpGet]
public string Get()
{
return "Hello World!";
}
}
}
如果希望程序启动时默认执行的方法为HomeController
中的Get
方法,则可以将launchSettings.json
中的launchUrl
属性设置为api/Home/Get
,代码如下:
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:3607",
"sslPort": 44303
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "api/Home/Get",// 修改URL
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"App": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "api/Home/Get",// 修改URL
"applicationUrl": "https://localhost:5001;http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
运行一下代码,发现浏览器能够正确输出Hello World!
。
3、appsettings.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"ConnectionString": "Data Source=DSF-PC;Initial Catalog=Dao;uid=sa;pwd=123456"
},
"AppSettings": {
"ApplicationName": "测试系统",
"PublishTime": "2022-01-01"
}
}
在ASP.NET Core
中,appsettings.json
主要负责存放应用程序的配置信息,与原先.NET Framework
时代的Web.config
在功能上几乎是一致的,只不过区别是一个用JSON
写配置,而另一个用的是XML
。
4、Startup.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace App
{
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.AddControllers();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
Startup.cs
文件是整个ASP.NET Core应用程序中的核心文件。它主要包含以下两个方法:
ConfigureServices
:添加应用服务Configure
:配置http
管道请求
4.1、ConfigureServices
如果你已经熟悉了.NET Core
中默认IoC
容器的使用方法,相信你在看到IServiceCollection
这个接口之后就已经明白了:这个方法就是用来注册接口和类的。新建一个接口和一个类,如下图所示:
其代码如下所示:
namespace App.Service
{
public interface ITestService
{
string GetMessage();
}
}
namespace App.Service
{
public class TestService : ITestService
{
public string GetMessage()
{
return "Hello World!";
}
}
}
然后在ConfigureServices
方法中注册一下ITestservice
和TestService
,代码如下:
using App.Service;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace App
{
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.AddControllers();
services.AddScoped<ITestService, TestService>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
最后修改一下HomeController
的代码,在其构造函数中注入ITestService
即可,代码如下:
using App.Service;
using Microsoft.AspNetCore.Mvc;
namespace App.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class HomeController : ControllerBase
{
private readonly ITestService service;
/// <summary>
/// 构造函数,注入ITestService
/// </summary>
/// <param name="service"></param>
public HomeController(ITestService service)
{
this.service = service;
}
[HttpGet]
public string Get()
{
return service.GetMessage();
}
}
}
运行一下代码,发现浏览器能够正确输出Hello World!
。
4.2、Configure
Configure
方法主要是用来配置http
请求的,通俗点讲:每次前端发送到后台的http
请求都会按照该方法内的验证规则进行验证,只有全部通过验证后才能返回需要的数据。后续博客将要介绍的Swagger
、跨域
、JWT鉴权
都会涉及到http
请求,因此在引入这些组件的同时也都需要在Configure
方法中进行配置。下面我们就利用Configure
方法来配置一下全局路由。现在我们是通过Controller
的Route
属性来配置,如下图所示:
可能有人会问:如果后续需要新建一系列的Controller
,难道每个Controller
都要手动修改Route
属性吗?答案当然是否定的!我们可以通过Configure
方法进行全局配置,其代码如下:
using App.Service;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace App
{
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.AddControllers();
services.AddScoped<ITestService, TestService>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "api/{controller}/{action}"
);
});
}
}
}
最后删除HomeController
的Route
和ApiController
标记属性即可,如下图所示:
运行一下代码,发现浏览器能够正确输出Hello World!
。
5、Programs.cs
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
namespace App
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
可能有人会奇怪:为什么Web API
应用程序会有一个Program.cs
?其实ASP.NET Core
应用程序本质上还是一个控制台程序。在原先.NET Framework
的时代,ASP.NET
是严重依赖于IIS
的,而ASP.NET Core
则是完全独立运行,因为它本身就包含一个内置的自托管的服务器,所以并不一定非要托管在IIS
上。但无论是托管还是自托管,宿主容器是必须的,因此Program.cs
就是用来在不同操作系统平台上构建宿主的。
6、结语
ASP.NET Core
应用程序的核心其实就是Startup.cs
文件,创建接口和类、注册接口和类、配置http
、注入控制器,这一套流程其实很简单。只要能够充分理解依赖注入和控制反转的思想,相信你一定可以快速上手ASP.NET Core
。