技术标签: c# .net
环境:
实验代码下载: https://download.csdn.net/download/u010476739/12320053
在使用asp.net core 进行api开发完成后,书写api说明文档对于程序员来说想必是件很痛苦的事情吧,但文档又必须写,而且文档的格式如果没有具体要求的话,最终完成的文档则完全取决于开发者的心情。或者详细点,或者简单点。那么有没有一种快速有效的方法来构建api说明文档呢?答案是肯定的, Swagger就是最受欢迎的REST APIs文档生成工具之一!
swagger官网:https://swagger.io/
参考:ASP.NET Core WebApi使用Swagger生成api说明文档看这篇就够了
这里新建一个空白的webapi项目即可。
<ItemGroup>
<PackageReference Include="Swashbuckle.AspNetCore" Version="5.6.3" />
</ItemGroup>
其实这个包里没有任何代码,只是打包了另外四个包的依赖:
- Swashbuckle.AspNetCore.Swagger
- Swashbuckle.AspNetCore.SwaggerGen
- Swashbuckle.AspNetCore.SwaggerUI
- Microsoft.Extensions.ApiDescription.Server
private readonly IWebHostEnvironment webHostEnvironment;
public Startup(IConfiguration configuration,IWebHostEnvironment webHostEnvironment)
{
Configuration = configuration;
this.webHostEnvironment= webHostEnvironment;
}
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.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo {
Title = "My API", Version = "v1" });
var xmlPath = Path.Combine(webHostEnvironment.ContentRootPath, Assembly.GetExecutingAssembly().GetName().Name + ".xml");
if (File.Exists(xmlPath))
{
options.IncludeXmlComments(xmlPath, true);
}
});
services.AddControllers();
}
说明:
注意上面代码中有指定生成的xml文档的地址,如果不指定的话,浏览器也会显示接口以及参数名称,但是就不会显示你写的注释,所以一定要手动将xml文档的地址配置上去。
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseSwagger();
app.UseSwaggerUI(options =>
{
options.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
//如果不想带/swagger路径访问的话,就放开下面的注释
//options.RoutePrefix = string.Empty;
});
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
浏览器中输入: http://localhost:5000/swagger
由上图可以看到Action
的方法描述都列出来了,此时可以点击右侧Try it out按钮,然后输入要传递到后台的参数以进行测试。
由上图可以看到Schemas中显示了模型WeatherForecast
,之所以显示它是因为有方法的参数或返回值引用到了这个模型。
如果你不想针对某个控制器或某个方法就在上面打上标记[ApiExplorerSettings(IgnoreApi = true)]
就行,这样浏览器页面中就不会出现这个控制器或方法了,如下图:
同理,如果这个方法不显示的话,那么因它而显示的模型也不会再显示了
上面是最简单的一个示例。一般我们做后台管理系统都是要有身份认证的,如果我们在swagger上测试后台方法那么我们必须在swagger页面上登录了才行!,下面以cookie认证为例说明。对cookie认证原理不清楚的可以参考:
.netcore入门10:分析aspnetcore自带的cookie认证原理
.netcore入门11:aspnetcore自带cookie的认证期限分析
.netcore入门12:aspnetcore中cookie认证之服务端保存认证信息
最终的代码如下:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie();
services.AddAuthorization();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseAuthentication();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
/// <summary>
/// cookie身份认证
/// </summary>
[Route("api/[controller]/[action]")]
[ApiController]
public class AuthController : ControllerBase
{
private readonly IConfiguration configuration;
public AuthController(IConfiguration configuration)
{
this.configuration = configuration;
}
/// <summary>
/// 登录方法
/// </summary>
/// <param name="username">用户名</param>
/// <param name="password">用户密码</param>
/// <returns></returns>
[HttpPost]
public async Task<object> Login([FromForm]string username, [FromForm]string password)
{
if (HttpContext.User.Identity.IsAuthenticated)
{
return Ok(new
{
Success = false,
Data = "不允许重复登录!"
});
}
if (username == "admin" && password == "1")
{
var claims = new Claim[] {
new Claim("id", "1") };
var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
var principal = new ClaimsPrincipal(identity);
await HttpContext.SignInAsync(principal);
return new
{
success = true,
data = "登录成功!"
};
}
else
{
return new
{
success = false,
data = "登录失败!"
};
}
}
/// <summary>
/// 登出
/// </summary>
/// <returns></returns>
[HttpGet]
[Authorize]
public async Task<object> LogOut()
{
await HttpContext.SignOutAsync();
return Ok(new
{
Success = true,
Data = "注销成功!"
});
}
}
首先看一下集成后的效果:
这里的弹框需要自定义,cookie本身并不支持,所以我们在集成的时候要手写这个文档页面(/swagger/ui/index.html)。
最终改造后的ConfigureServices
方法如下:
public void ConfigureServices(IServiceCollection services)
{
services.AddSwaggerGen(options =>
{
//定义api文档
options.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo {
Title = "My API", Version = "v1" });
//包含vs生成的注释文档
var xmlPath = Path.Combine(webHostEnvironment.ContentRootPath, Assembly.GetExecutingAssembly().GetName().Name + ".xml");
if (File.Exists(xmlPath))
{
options.IncludeXmlComments(xmlPath, true);
}
//描述安全信息
options.AddSecurityDefinition(CookieAuthenticationDefaults.AuthenticationScheme, new OpenApiSecurityScheme()
{
Name = CookieAuthenticationDefaults.AuthenticationScheme,
Scheme = CookieAuthenticationDefaults.AuthenticationScheme
});
});
services.AddControllers();
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie();
services.AddAuthorization();
}
最终改造后的Configure
方法如下:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseStaticFiles();
app.UseHttpsRedirection();
app.UseSwagger();
app.UseSwaggerUI(options =>
{
options.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
//如果不想带/swagger路径访问的话,就放开下面的注释
//options.RoutePrefix = string.Empty;
//使用自定义的页面(主要是增加友好的身份认证体验)
string path = Path.Combine(env.WebRootPath, "swagger/ui/index.html");
if (File.Exists(path)) options.IndexStream = () => new MemoryStream(File.ReadAllBytes(path));
});
app.UseAuthentication();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
本案例使用的是webapi项目,没有自带wwwroot文件夹,所以需要自己建个文件夹,最终目录结构如下图:
我们上一步指定webapi的接口文档的首页是index.html页面,现在我们就来编辑它:
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>%(DocumentTitle)</title>
<link href="https://fonts.googleapis.com/css?family=Open+Sans:400,700|Source+Code+Pro:300,600|Titillium+Web:400,600,700"
rel="stylesheet">
<link rel="stylesheet" type="text/css" href="./swagger-ui.css">
<link rel="icon" type="image/png" href="./favicon-32x32.png" sizes="32x32" />
<link rel="icon" type="image/png" href="./favicon-16x16.png" sizes="16x16" />
<style>
html {
box-sizing: border-box;
overflow: -moz-scrollbars-vertical;
overflow-y: scroll;
}
*,
*:before,
*:after {
box-sizing: inherit;
}
body {
margin: 0;
background: #fafafa;
}
</style>
%(HeadContent)
</head>
<body>
<div id="swagger-ui"></div>
<script src="swagger-ui-bundle.js"></script>
<script src="swagger-ui-standalone-preset.js"></script>
<script src="ui/auth.js"></script>
<script>
window.onload = function () {
var configObject = JSON.parse('%(ConfigObject)');
// Apply mandatory parameters
configObject.dom_id = "#swagger-ui";
configObject.presets = [SwaggerUIBundle.presets.apis, SwaggerUIStandalonePreset];
configObject.layout = "StandaloneLayout";
configObject.requestInterceptor = function (request) {
//do something
return request;
};
if (!configObject.hasOwnProperty("oauth2RedirectUrl")) {
configObject.oauth2RedirectUrl = window.location + "oauth2-redirect.html"; // use the built-in default
}
function getAuthorizeButtonText() {
return auth.hasLogin() ? 'Logout' : 'Authorize';
}
function getAuthorizeButtonCssClass() {
return auth.hasLogin() ? 'cancel' : 'authorize';
}
configObject.plugins = [
function (system) {
return {
components: {
authorizeBtn: function () {
return system.React.createElement("button",
{
id: "authorize",
className: "btn " + getAuthorizeButtonCssClass(),
style: {
lineHeight: "normal"
},
onClick: function () {
var authorizeButton = document.getElementById('authorize');
auth.logout(function () {
authorizeButton.innerText = getAuthorizeButtonText();
authorizeButton.className = 'btn ' + getAuthorizeButtonCssClass();
});
if (!auth.hasLogin()) {
auth.openAuthDialog(function () {
authorizeButton.innerText = getAuthorizeButtonText();
authorizeButton.className = 'btn ' + getAuthorizeButtonCssClass();
auth.closeAuthDialog();
});
}
}
}, getAuthorizeButtonText());
}
}
}
}
];
// Build a system
SwaggerUIBundle(configObject);
}
</script>
</body>
</html>
从index.html页面中我们看到,我们根据后台接口的定义渲染了文档并创建了认证按钮(Authorize),并且给这个按钮绑定了事件。
下面看下前端认证的代码脚本(auth.js):
auth.js:
var auth = window.auth || {
};
//这个'tokenCookieName '可以删除,本来我是想把登录返回的cookie值在localstorage中再存一份
auth.tokenCookieName = "aspnetcore.authauth";
auth.loginUrl = "/api/Auth/Login";
auth.logoutUrl = "/api/Auth/Logout";
auth.logout = function (callback) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
var res = JSON.parse(xhr.responseText);
if (!res.success) {
console.warn(res.data);
return;
}
localStorage.removeItem("auth.hasLogin");
callback();
} else {
console.warn("Logout failed !");
}
}
};
xhr.open('Get', auth.logoutUrl, true);
xhr.send();
}
auth.hasLogin = function () {
return localStorage.getItem("auth.hasLogin");
}
auth.openAuthDialog = function (loginCallback) {
auth.closeAuthDialog();
var authAuthDialog = document.createElement('div');
authAuthDialog.className = 'dialog-ux';
authAuthDialog.id = 'auth-auth-dialog';
document.getElementsByClassName("swagger-ui")[1].appendChild(authAuthDialog);
// -- backdrop-ux
var backdropUx = document.createElement('div');
backdropUx.className = 'backdrop-ux';
authAuthDialog.appendChild(backdropUx);
// -- modal-ux
var modalUx = document.createElement('div');
modalUx.className = 'modal-ux';
authAuthDialog.appendChild(modalUx);
// -- -- modal-dialog-ux
var modalDialogUx = document.createElement('div');
modalDialogUx.className = 'modal-dialog-ux';
modalUx.appendChild(modalDialogUx);
// -- -- -- modal-ux-inner
var modalUxInner = document.createElement('div');
modalUxInner.className = 'modal-ux-inner';
modalDialogUx.appendChild(modalUxInner);
// -- -- -- -- modal-ux-header
var modalUxHeader = document.createElement('div');
modalUxHeader.className = 'modal-ux-header';
modalUxInner.appendChild(modalUxHeader);
var modalHeader = document.createElement('h3');
modalHeader.innerText = 'Authorize';
modalUxHeader.appendChild(modalHeader);
// -- -- -- -- modal-ux-content
var modalUxContent = document.createElement('div');
modalUxContent.className = 'modal-ux-content';
modalUxInner.appendChild(modalUxContent);
modalUxContent.onkeydown = function (e) {
if (e.keyCode === 13) {
//try to login when user presses enter on authorize modal
auth.login(loginCallback);
}
};
//Inputs
createInput(modalUxContent, 'userName', 'Username or email address');
createInput(modalUxContent, 'password', 'Password', 'password');
//Buttons
var authBtnWrapper = document.createElement('div');
authBtnWrapper.className = 'auth-btn-wrapper';
modalUxContent.appendChild(authBtnWrapper);
//Close button
var closeButton = document.createElement('button');
closeButton.className = 'btn modal-btn auth btn-done button';
closeButton.innerText = 'Close';
closeButton.style.marginRight = '5px';
closeButton.onclick = auth.closeAuthDialog;
authBtnWrapper.appendChild(closeButton);
//Authorize button
var authorizeButton = document.createElement('button');
authorizeButton.className = 'btn modal-btn auth authorize button';
authorizeButton.innerText = 'Login';
authorizeButton.onclick = function () {
auth.login(loginCallback);
};
authBtnWrapper.appendChild(authorizeButton);
}
auth.closeAuthDialog = function () {
if (document.getElementById('auth-auth-dialog')) {
document.getElementsByClassName("swagger-ui")[1].removeChild(document.getElementById('auth-auth-dialog'));
}
}
auth.login = function (callback) {
var usernameOrEmailAddress = document.getElementById('userName').value;
if (!usernameOrEmailAddress) {
alert('Username or Email Address is required, please try with a valid value !');
return false;
}
var password = document.getElementById('password').value;
if (!password) {
alert('Password is required, please try with a valid value !');
return false;
}
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
var res = JSON.parse(xhr.responseText);
if (!res.success) {
alert(res.data);
return;
}
localStorage.setItem("auth.hasLogin", true);
callback();
} else {
alert('Login failed !');
}
}
};
xhr.open('POST', auth.loginUrl, true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send("username=" + encodeURIComponent(usernameOrEmailAddress) + "&password=" + password);
}
function createInput(container, id, title, type) {
var wrapper = document.createElement('div');
wrapper.className = 'wrapper';
container.appendChild(wrapper);
var label = document.createElement('label');
label.innerText = title;
wrapper.appendChild(label);
var section = document.createElement('section');
section.className = 'block-tablet col-10-tablet block-desktop col-10-desktop';
wrapper.appendChild(section);
var input = document.createElement('input');
input.id = id;
input.type = type ? type : 'text';
input.style.width = '100%';
section.appendChild(input);
}
从auth.js脚本中我们可以看到:后台登录的接口地址、登出的接口地址,以及登录、登出的逻辑。
调试运行后,在浏览器输入:https://localhost:5001/swagger/index.html
,可以看到按钮Authorize
,,点击后如下:
输入用户名和密码:(admin 1),回车:
可以看到,已经显示登录了,此时你可以打开调试,观察cookie和localstore:
从上图中看到,认证后的cookie已保存,并且将是否登录的标记也保存到了localstorage(为什么要存储这个标记?因为这个cookie是httponly的,js操作不了。。。),此时你刷新这个页面会看到一直显示登录状态。
当我们在登录状态时,点击Logout
按钮,我们就退出登录了,此时再查看cookie和localstorage中的存储,我们会发现,认证时产生的cookie和标记都被清理了。
从上面的介绍我们知道了怎么给webapi的接口页面定制登录和登出功能,但一般登录时都会有验证码之类的其他选项,此时你只需要在登录对话框上添加自己需要的即可。
文章浏览阅读1.3w次。转载自 http://www.miui.com/thread-2003672-1-1.html 当手机在刷错包或者误修改删除系统文件后会出现无法开机或者是移动定制(联通合约机)版想刷标准版,这时就会用到线刷,首先就是安装线刷驱动。 在XP和win7上线刷是比较方便的,用那个驱动自动安装版,直接就可以安装好,完成线刷。不过现在也有好多机友换成了win8/8.1系统,再使用这个_mt65驱动
文章浏览阅读1k次。SonarQube是一个代码质量管理平台,可以扫描监测代码并给出质量评价及修改建议,通过插件机制支持25+中开发语言,可以很容易与gradle\maven\jenkins等工具进行集成,是非常流行的代码质量管控平台。通CheckStyle、findbugs等工具定位不同,SonarQube定位于平台,有完善的管理机制及强大的管理页面,并通过插件支持checkstyle及findbugs等既有的流..._sonar的客户端区别
文章浏览阅读3.4k次,点赞2次,收藏27次。神经图灵机是LSTM、GRU的改进版本,本质上依然包含一个外部记忆结构、可对记忆进行读写操作,主要针对读写操作进行了改进,或者说提出了一种新的读写操作思路。神经图灵机之所以叫这个名字是因为它通过深度学习模型模拟了图灵机,但是我觉得如果先去介绍图灵机的概念,就会搞得很混乱,所以这里主要从神经图灵机改进了LSTM的哪些方面入手进行讲解,同时,由于模型的结构比较复杂,为了让思路更清晰,这次也会分开几..._神经图灵机方法改进
文章浏览阅读2.8k次。一、模型迭代方法机器学习模型在实际应用的场景,通常要根据新增的数据下进行模型的迭代,常见的模型迭代方法有以下几种:1、全量数据重新训练一个模型,直接合并历史训练数据与新增的数据,模型直接离线学习全量数据,学习得到一个全新的模型。优缺点:这也是实际最为常见的模型迭代方式,通常模型效果也是最好的,但这样模型迭代比较耗时,资源耗费比较多,实时性较差,特别是在大数据场景更为困难;2、模型融合的方法,将旧模..._模型迭代
文章浏览阅读2.3k次。1、前言上传图片一般采用异步上传的方式,但是异步上传带来不好的地方,就如果图片有改变或者删除,图片服务器端就会造成浪费。所以有时候就会和参数同步提交。笔者喜欢base64图片一起上传,但是图片过多时就会出现数据丢失等异常。因为tomcat的post请求默认是2M的长度限制。2、解决办法有两种:① 修改tomcat的servel.xml的配置文件,设置 maxPostSize=..._base64可以装换zip吗
文章浏览阅读1k次,点赞17次,收藏22次。Opencv自然场景文本识别系统(源码&教程)_opencv自然场景实时识别文字
文章浏览阅读1.3k次。拷贝虚拟机文件时间比较长,因为虚拟机 flat 文件很大,所以要等。脚本完成后,以复制虚拟机文件夹。将以下脚本内容写入文件。_exsi6.7快速克隆centos
文章浏览阅读2k次。本文主要实现基于二度好友的推荐。数学公式参考于:http://blog.csdn.net/qq_14950717/article/details/52197565测试数据为自己随手画的关系图把图片整理成文本信息如下:a b c d e f yb c a f gc a b dd c a e h q re f h d af e a b gg h f bh e g i di j m n ..._本关任务:使用 spark core 知识完成 " 好友推荐 " 的程序。
文章浏览阅读367次。南京大学高级程序设计期末复习总结,c++面向对象编程_南京大学高级程序设计
文章浏览阅读3.1k次,点赞2次,收藏12次。实现朴素贝叶斯分类器,并且根据李航《统计机器学习》第四章提供的数据训练与测试,结果与书中一致分别实现了朴素贝叶斯以及带有laplace平滑的朴素贝叶斯%书中例题实现朴素贝叶斯%特征1的取值集合A1=[1;2;3];%特征2的取值集合A2=[4;5;6];%S M LAValues={A1;A2};%Y的取值集合YValue=[-1;1];%数据集和T=[ 1,4,-1;..._朴素贝叶斯 matlab训练和测试输出
文章浏览阅读1.6k次。Markdown 文本换行_markdowntext 换行
文章浏览阅读6.7w次,点赞2次,收藏37次。win10 2016长期服务版激活错误解决方法:打开“注册表编辑器”;(Windows + R然后输入Regedit)修改SkipRearm的值为1:(在HKEY_LOCAL_MACHINE–》SOFTWARE–》Microsoft–》Windows NT–》CurrentVersion–》SoftwareProtectionPlatform里面,将SkipRearm的值修改为1)重..._错误: 0xc0000022 在运行 microsoft windows 非核心版本的计算机上,运行“slui.ex