您的位置:首页 > Web前端 > Vue.js

《Asp.Net Core3 + Vue3入坑教程》-Net Core项目搭建与Swagger配置步骤

2021-02-26 22:56 1466 查看

简介

《Asp.Net Core3 + Vue3入坑教程》 此教程仅适合新手入门或者前后端分离尝试者。可以根据图文一步一步进操作编码也可以选择直接查看源码。每一篇文章都有对应的源码

教程后期会将 .Net Core 3升级成 .Net Core 5

目录

《Asp.Net Core3 + Vue3入坑教程》系列教程目录

Asp.Net Core后端项目

  1. 后端项目搭建与Swagger配置步骤
  2. (暂未发表敬请期待...)CORS跨域问题处理
  3. (暂未发表敬请期待...)AutoMapper & Restful API
  4. (暂未发表敬请期待...)EF Core & Postgresql
  5. (暂未发表敬请期待...).Net Core 3升级成 .Net Core 5
  6. (暂未发表敬请期待...)JWT

Vue3 前端项目

暂未发表敬请期待...

本文简介

本文为《Asp.Net Core3 + Vue3入坑教程》系列教程的后端开篇,主要介绍 Asp.Net Core Web后端项目的搭建流程与Swagger配置。

Simple项目搭建流程与Swagger配置步骤

新建项目



引入Swagger Nuget包


配置Starup.cs

代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Simple_Asp.Net_Core.ServiceProvider;

namespace Simple_Asp.Net_Core
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddSwagger();
}

// 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.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "ApiHelp V1");
});
}

app.UseRouting();
app.UseEndpoints(endpoints => endpoints.MapDefaultControllerRoute());
}
}
}

配置XML 文档文件

目的是让项目的注释能够展示在swagger页面上 。XML 文档文件的路径需要与下一步Swagger扩展类的文件路径一致

var xmlPath = Path.Combine(basePath, "Simple_Asp.Net_Core.xml");


新建文件夹ServiceProvider,增加Swagger扩展类

当前Swagger扩展类,包含了很多内容,后续会陆续使用上

代码如下:

using System;
using System.IO;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;

namespace Simple_Asp.Net_Core.ServiceProvider
{
public static class Swagger
{
public static void AddSwagger(this IServiceCollection services)
{
services.AddSwaggerGen(option =>
{
option.SwaggerDoc("v1", new OpenApiInfo
{
Version = "0.0.1",
Title = "Simple API",
Description = "框架说明文档",
TermsOfService = null,
Contact = new OpenApiContact { Name = "Simple", Email = string.Empty, Url = null }
});

// 读取xml信息
var basePath = AppContext.BaseDirectory;
var xmlPath = Path.Combine(basePath, "Simple_Asp.Net_Core.xml");option.IncludeXmlComments(xmlPath, true);

// Add security definitions
option.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
{

ad8
Description = "Please enter into field the word 'Bearer' followed by a space and the JWT value",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey,
});
option.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{ new OpenApiSecurityScheme
{
Reference = new OpenApiReference()
{
Id = "Bearer",
Type = ReferenceType.SecurityScheme
}
}, Array.Empty<string>() }
});
});
}
}
}

修改launchSettings.json

目的是让项目启动页为Swagger页面

新建Controllers文件夹,新增ValuesController

代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace Simple_Asp.Net_Core.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
// GET: api/<ValuesController1>
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}

// GET api/<ValuesController1>/5
[HttpGet("{id}")]
public string Get(int id)
{
return "value";
}

// POST api/<ValuesController1>
[HttpPost]
public void Post([FromBody] string value)
{
}

// PUT api/<ValuesController1>/5
[HttpPut("{id}")]
public void Put(int id, [FromBody] string value)
{
}

// DELETE api/<ValuesController1>/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
}

运行网站

利用swagger调用接口

请求结果返回404的错误,发现路由配置错误,修改路由配置

再次运行项目,调用接口,这一次成功返回消息!

最后一步取消警告

由于引入了Swagger导致VS多了CS1591警告,也可以不取消此警告

Simple项目的搭建与Swagger配置结束!

总结

Swagger作为前后端分离开 ad8 发必备工具,不仅可以作为前后端同事交流的文档也有助于我们更直观的管理API文档。在开发过程中针对Controller的职能与用途,需要做好必要注释、良好的注释为前后端交流和后期维护都有很重要的作用。

GitHub源码

注意:源码调试过程中如果出现xml文件路径错误,需要参照Swagger配置“配置XML 文档文件”步骤,取消勾选然后再选中 ,将XML路径设置成与你的电脑路径匹配!

https://github.com/Impartsoft/Simple_Asp.Net_Core/tree/master/Simple_Asp.Net_Core 1.Swagger

参考资料

博客(推荐学习) https://www.geek-share.com/detail/2745517460.html

微软官方文档 https://docs.microsoft.com/zh-cn/aspnet/core/?view=aspnetcore-5.0

Swagger官网 https://swagger.io/

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐