本人菜鸟,最近想自己从头开始搭个前后端分离的开发框架,记录一下:
第一步:新建.Net Core的API项目
以上步骤结束后,一个API项目就创建好了。
第二步:使用Swagger
鼠标右击下图所示依赖项,选择【管理NuGet程序包】
搜索【Swashbuckle.AspNetCore】,安装Swagger包如下图:
安装完毕后,设置项目属性中的【生成】,把输出XML勾上,这样是为了后续Swagger方便读取方法等的注释,
配置完毕后,需要给所有的方法或者类加上注释,三条斜杠的那种,否则会有警告。
如下图:
以上步骤结束后,配置Startup文件如下:
/// <summary>
///
/// </summary>
public class Startup
{
/// <summary>
///
/// </summary>
/// <param name="configuration"></param>
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
/// <summary>
///
/// </summary>
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
/// <summary>
///
/// </summary>
/// <param name="services"></param>
public void ConfigureServices(IServiceCollection services)
{
#region Swagger
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info
{
Version = "v0.1.0",
Title = "SwaggerTest API",
Description = "框架说明文档",
TermsOfService = "None",
Contact = new Swashbuckle.AspNetCore.Swagger.Contact { Name = "SwaggerTest", Email = "[email protected]", Url = "https://www.xxx.com" }
});
var basePath = PlatformServices.Default.Application.ApplicationBasePath;
var xmlPath = Path.Combine(basePath, "SwaggerTest.xml");//这个就是刚刚配置的xml文件名
c.IncludeXmlComments(xmlPath, true);//默认的第二个参数是false,这个是controller的注释,记得修改
});
#endregion
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
/// <summary>
///
/// </summary>
/// <param name="app"></param>
/// <param name="env"></param>
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
#region Swagger
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "ApiHelp V1");
c.RoutePrefix = ""; //路径配置,设置为空,表示直接在根域名(localhost:8001)访问该文件,注意localhost:8001/swagger是访问不到的,去launchSettings.json把launchUrl去掉
});
#endregion
app.UseMvc();
}
}
最后把项目中【launchSettings.json】里的初始Url删掉就可以了,如下图:
控制器中下图问题是因为没加注释,加完注释就OK了
然后编译运行:
以上就是全部内容了。