目录
1、1:创建.NET Core API框架
1、2:集成Swagger
1、3:搭建完整的项目结构
1:创建.NET Core API框架
选择Web>.NET Core>ASP.NET Core Web 应用程序
选择API 确定即可
2:集成Swagger
1、使用PM>Install-Package Swashbuckle.SwaggerUi.Master -Version 6.0.0-T2016120822
2、使用Nuget项目管理工具 搜索Swashbuckle.SwaggerUi 勾选包括预发行版
打开程序主入口Startup 配置swagger
这时候我们发现,直接AddSwaggerGen是找不到该方法,因为我们还要添加Nuget包;
调用程序包管理器控制台 PM>Install-Package Swashbuckle.AspNetCore -Version 3.0.0
使用过Swagger 的朋友应该都知道,Swagger还有一个很强大的功能就是呈现注释,那我们要如何解析xml中的注释呢?
第一步:右击我们的项目,进入属性>生成>XML文档文件 保存
第二步:代码如下
using System.IO;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.PlatformAbstractions;
using Swashbuckle.AspNetCore.Swagger;
namespace Dianshi.P2P.Core.JPush.WebApi
{
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();
// Add Swagger UI.
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info
{
Version = "v1",
Title = "JPushAPI",
Description = "A simple example ASP.NET Core Web API",
TermsOfService = "None",
Contact = new Contact { Name = "旺仔小舒舒的博客", Email = "", Url = "https://blog.csdn.net/qq_35193189" },
});
c.IncludeXmlComments(Path.Combine(PlatformServices.Default.Application.ApplicationBasePath, "Dianshi.P2P.Core.JPush.WebApi.XML")); // 注意:此处替换成所生成的XML documentation的文件名。
c.DescribeAllEnumsAsStrings();
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseMvc();
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "JPush.WebApi V1");
});
}
}
}
这时候我们发现 PlatformServices 找不到?这是因为我们缺少程序包;
打开程序包管理器控制台:PM>Install-Package Microsoft.Extensions.PlatformAbstractions -Version 1.1.0
3、搭建完成的项目结构
写过接口的朋友应该都知道,当接口偏多的时候,我们把所有接口堆积到Controllers中,看起来非常乱;如果想要找到某个Controllers那是非常负责的;说到这里,我们马上想到的是分组,没错,就是创建区域;
这是我们默认的结构,熟悉我们把Controllers删除,右键项目>添加区域
输入区域名:例如 权限管理(AuthorizationManage) 销售管理(SaleManage)等等;
此时的目录结构就非常清楚,团队开放个人负责的模块很清晰;
那么问题又来了,那路由需要我们自己配置吗?微软都为我们考虑到了,.NET Core 路由配置更为简单;
Route 默认指定是controller 自己也可以修改到action
api/[controller]/[action]
是不是非常简单呢?是的,很简单
最后我们在配置一下默认启动页面吧;
打开 Properties>launchSettings.json
将api/values 修改为:swagger/index.html
哈哈哈哈,希望此文档对你们有所帮助;
最后 我们运行项目吧;Ctrl+F5