ASP.NET Core 3.1系列(3)——创建第一个Web API应用程序

32 篇文章 42 订阅

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方法中注册一下ITestserviceTestService,代码如下:

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方法来配置一下全局路由。现在我们是通过ControllerRoute属性来配置,如下图所示:
在这里插入图片描述
可能有人会问:如果后续需要新建一系列的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}"
                );
            });
        }
    }
}

最后删除HomeControllerRouteApiController标记属性即可,如下图所示:
在这里插入图片描述
运行一下代码,发现浏览器能够正确输出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

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值