本篇分为以下几个部分:

Swagger的简单应用

1、首先新建一个Api项目

2、使用Nuget添加Swashbuckle.AspNetCore,我使用的版本为1.1.0(版本不一样,后面的配置可能不一样)
 
3、为了在swagger上显示注释,右键项目MiniprofilerApi,属性=>生成=>输出为XML文档文件
 
4、右键项目=>编辑.csproj添加如下代码,避免一些警告:
 

4、在Startup类的ConfigureServices方法和Configure方法中配置如下:

5、添加接口注释:

6、修改项目运行端口,访问路径,关闭ssl,右键项目=>属性=>调试,配置如下:

7、启动项目,界面效果如下:

Miniprofier的后台配置

1、安装MiniProfiler.AspNetCore.Mvc

2、在Startup类的ConfigureServices方法和Configure方法中配置如下:

3、运行程序:访问http://localhost:5000/mini-profiler-resources/results

跨域配置:

在angular中显示Miniprofier

1、在页面创建Miniprofier需要的js和css

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http'; @Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent { private src: string = 'http://localhost:5000/mini-profiler-resources/';
private scriptSrc: string = `${this.src}includes.min.js`;
private cssSrc: string = `${this.src}includes.min.css`; private id: string = 'mini-profiler';
private dataPath: string = `${this.src}`;
private dataVersion: string = '';
private dataPosition: string = 'right';
private dataChildren: boolean = true;
private dataMaxTraces: number = 35;
private dataAuthorized: boolean = true;
private dataStartHidden: string = 'false';
private dataToggleShortcut: string = 'Alt+P';
private dataTrivialMilliseconds: number = 35;
private dataTrivial: boolean = true;
private dataControls: boolean = true;
private dataCurrentId: string = '';
private dataIds: string = '';
private scriptAsync: boolean = true;
private innerHTML: string = ''; constructor(private http: HttpClient){
} ngAfterViewInit(): void {
//添加Miniprofier的js
this.appendDivElement();
//添加Miniprofier的css
this.appendCssLink();
} //请求后台接口
send(): void{
let serverurl: string = "http://localhost:5000//api/Values"; this.http.get(serverurl)
.toPromise()
.then(response => {
console.log()
}).catch(error => {
});
} private appendDivElement(): void {
const body = document.body as HTMLDivElement;
const script = document.createElement('script');
script.innerHTML = this.innerHTML;
script.src = this.scriptSrc;
script.setAttribute('data-version', this.dataVersion);
script.setAttribute('data-path', this.dataPath);
script.setAttribute('data-position', this.dataPosition);
script.setAttribute('id', this.id);
script.setAttribute('data-current-id', this.dataCurrentId);
script.setAttribute('data-ids', this.dataIds);
script.setAttribute('data-trivial', this.dataTrivial.toString());
script.setAttribute('data-children', this.dataChildren.toString());
script.setAttribute('data-max-traces', this.dataMaxTraces.toString());
script.setAttribute('data-controls', this.dataControls.toString());
script.setAttribute('data-authorized', this.dataAuthorized.toString());
script.setAttribute('data-start-hidden', this.dataStartHidden.toString());
script.setAttribute('data-toggle-shortcut', this.dataToggleShortcut);
script.setAttribute('data-trivial-milliseconds', this.dataTrivialMilliseconds.toString());
script.async = this.scriptAsync;
body.appendChild(script);
} private appendCssLink(): void {
const body = document.body as HTMLDivElement;
const css = document.createElement('link');
css.href = this.cssSrc;
css.rel = 'stylesheet'; body.appendChild(css);
}
}

2、添加Http拦截器,动态显示监听结果

import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpHandler, HttpRequest, HttpEvent, HttpResponse, HttpHeaders }
from '@angular/common/http'; import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators'; declare var MiniProfiler: any; @Injectable()
export class MiniProfilerInterceptor implements HttpInterceptor {
intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
return next.handle(req).pipe(
tap(evt => {
if (evt instanceof HttpResponse) {
if (evt && evt.headers) {
this.makeMiniProfilerRequests(evt.headers);
}
}
})
)
} private makeMiniProfilerRequests(headers: HttpHeaders) {
const miniProfilerHeaders = headers.getAll('x-miniprofiler-ids'); if (!miniProfilerHeaders) {
return;
} miniProfilerHeaders.forEach(miniProfilerIdHeaderValue => {
const ids = JSON.parse(miniProfilerIdHeaderValue) as string[];
MiniProfiler.fetchResults(ids);
}); }
}

3、在app.module.ts中的配置

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core'; import { AppComponent } from './app.component';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { MiniProfilerInterceptor } from './mini-profiler-http'; @NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule
],
providers: [{
provide: HTTP_INTERCEPTORS,
useClass: MiniProfilerInterceptor, multi: true
}],
bootstrap: [AppComponent]
})
export class AppModule { }

4、在app.component.html页面添加一个请求按钮

<div style="text-align:center;margin:100px auto">
<button (click)="send()">click</button>
</div>

5、页面效果

在vue中显示Miniprofier

和在angular中的操作步骤一致,下面放主要代码:

1、App.vue 主组件

<template>
<div id="app">
<MiniProfiler
:scriptSrc="scriptSrc"
:dataPath="src"
:cssSrc="cssSrc"/>
<Dummy />
</div>
</template> <script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import MiniProfiler from './components/MiniProfiler.vue';
import Dummy from './components/Dummy.vue';
import axios from 'axios'; @Component({
components: {
MiniProfiler,
Dummy,
},
})
export default class App extends Vue {
private src: string = 'http://localhost:5000/mini-profiler-resources/';
private scriptSrc: string = `${this.src}includes.min.js`;
private cssSrc: string = `${this.src}includes.min.css`;
}
</script> <style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>

2、Dummy.vue 子组件用于发送接口请求

<template>
<button type="button" @click="getProfiler">Click Me!</button>
</template> <script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import axios from 'axios'; @Component
export default class Dummy extends Vue {
private getProfiler() {
axios.get('http://localhost:5000/api/values');
}
}
</script>

3、MiniProfiler.vue 子组件用于添加拦截器和创建Miniprofier需要的js和css

<template>
</template> <script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator';
import axios from 'axios'; @Component
export default class MiniProfiler extends Vue {
@Prop({ default: 'mini-profiler' }) private id!: string;
@Prop() private scriptSrc!: string;
@Prop() private cssSrc!: string;
@Prop() private dataPath!: string;
@Prop({ default: '' }) private dataVersion!: string;
@Prop({ default: 'right' }) private dataPosition!: string;
@Prop({ default: true }) private dataChildren!: boolean;
@Prop({ default: 35 }) private dataMaxTraces!: number;
@Prop({ default: true }) private dataAuthorized!: boolean;
@Prop({ default: false }) private dataStartHidden!: string;
@Prop({ default: 'Alt+P' }) private dataToggleShortcut!: string;
@Prop({ default: 35 }) private dataTrivialMilliseconds!: number;
@Prop({ default: true }) private dataTrivial!: boolean;
@Prop({ default: true }) private dataControls!: boolean;
@Prop({ default: '' }) private dataCurrentId!: string;
@Prop({ default: '' }) private dataIds!: string;
@Prop({ default: true }) private scriptAsync!: boolean;
@Prop({ default: '' }) private innerHTML!: string; private created(): void {
this.axiosSetUp();
this.appendDivElement();
this.appendCssLink();
} private axiosSetUp(): void {
const key: string = 'MiniProfiler';
axios.interceptors.response.use(function success(config) {
const miniProfiler: any = (window as any)[key]; const miniProfilerIds = JSON.parse(config.headers['x-miniprofiler-ids']) as string[];
miniProfiler.fetchResults(miniProfilerIds);
return config;
}, function bug(error) {
return Promise.reject(error);
});
} private appendDivElement(): void {
const body = document.body as HTMLDivElement;
const script = document.createElement('script');
script.innerHTML = this.innerHTML;
script.src = this.scriptSrc;
script.setAttribute('data-version', this.dataVersion);
script.setAttribute('data-path', this.dataPath);
script.setAttribute('data-position', this.dataPosition);
script.setAttribute('id', this.id);
script.setAttribute('data-current-id', this.dataCurrentId);
script.setAttribute('data-ids', this.dataIds);
script.setAttribute('data-trivial', this.dataTrivial.toString());
script.setAttribute('data-children', this.dataChildren.toString());
script.setAttribute('data-max-traces', this.dataMaxTraces.toString());
script.setAttribute('data-controls', this.dataControls.toString());
script.setAttribute('data-authorized', this.dataAuthorized.toString());
script.setAttribute('data-start-hidden', this.dataStartHidden.toString());
script.setAttribute('data-toggle-shortcut', this.dataToggleShortcut);
script.setAttribute('data-trivial-milliseconds', this.dataTrivialMilliseconds.toString());
script.async = this.scriptAsync; body.appendChild(script);
} private appendCssLink(): void {
const body = document.body as HTMLDivElement;
const css = document.createElement('link');
css.href = this.cssSrc;
css.rel = 'stylesheet'; body.appendChild(css);
}
}
</script>

4、界面效果

在swagger中显示Miniprofier

1、将性能分析监测信息从后端发送到Swagger界面。

首先给swagger添加拦截器

拦截器代码如下:

using Microsoft.AspNetCore.Http;
using StackExchange.Profiling;
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen; namespace MiniprofilerApi.MiniProfierHelp
{
public class InjectMiniProfiler : IDocumentFilter
{
private readonly IHttpContextAccessor _httpContext;
public InjectMiniProfiler(IHttpContextAccessor httpContext)
{
_httpContext = httpContext;
}
public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context)
{
swaggerDoc.Info.Contact = new Contact()
{
Name = MiniProfiler.Current.RenderIncludes(_httpContext.HttpContext).ToString()
};
}
}
}

此时运行项目,swagger界面显示如下:

2、通过js解析MIniprofier的脚本,代码如下:

(function () {
window.angular=true; //Create a mini profiler script tag with the right properites
var MiniProfiler = $('#api_info > div:nth-child(3)').text(); const attributes = [
'src', 'data-version', 'data-path', 'data-current-id', 'data-ids',
'data-position', 'data-trivial-milliseconds', 'data-max-traces',
'data-authorized', 'data-toggle-shortcut', 'data-ignored-duplicate-execute-types'
]; var GetAttr = function (input, attributeName) {
const myRegexp = attributeName + '="(.*?)"';
const re = new RegExp(myRegexp, "g");
const match = re.exec(input);
return match[1];
}
var s = document.createElement("script");
s.type = "text/javascript";
s.id = "mini-profiler";
s.async = true; for (var i = 0; i < attributes.length; i++) {
var element = attributes[i];
s.setAttribute(element, GetAttr(MiniProfiler, element));
} document.body.appendChild(s); // Remove injected tag from view
$('#api_info > div:nth-child(3)').text('');
})();

配置swagger执行js:

3、界面效果如下:

全部源代码见:https://github.com/zrkcode/Miniprofiler.git

监听EF执行的Sql语句或更多NetCore+Miniprofiler相关配置见:https://miniprofiler.com/dotnet/AspDotNetCore

更多Swagger+NetCore配置见:https://docs.microsoft.com/en-us/aspnet/core/tutorials/getting-started-with-swashbuckle?view=aspnetcore-2.2&tabs=visual-studio

Miniprofiler在swagger、vue、angular中的使用的更多相关文章

  1. angular.js和vue.js中实现函数去抖(debounce)

    问题描述 搜索输入框中,只当用户停止输入后,才进行后续的操作,比如发起Http请求等. 学过电子电路的同学应该知道按键防抖.原理是一样的:就是说当调用动作n毫秒后,才会执行该动作,若在这n毫秒内又调用 ...

  2. Vue.js中Directive知识

    近期所学的Vue.js这个MVVM前端技术缓解了我一直愁于前后端开发杂糅所带来的痛苦.今天就来说说关于Vue.js里面的Directive知识. Directive Directive看上去虽然和An ...

  3. Angular中的数据绑定

    (1)HTML绑定:{{}} (2)属性绑定:[] 注意:属性绑定通常赋值为变量,如果赋值为常量(如字符串常量) 必须用引号括起来,如<img [src]="'../../assets ...

  4. .net core WebAPI性能监控-MiniProfiler与Swagger集成

    ------------恢复内容开始------------ 安装Nuget Install-Package MiniProfiler.AspNetCore.Mvc Install-Package M ...

  5. Angular中ngCookies模块介绍

    1.Cookie介绍 Cookie总是保存在客户端中,按在客户端中的存储位置,可分为内存Cookie和硬盘Cookie.内存Cookie由浏览器维护,保存在内存中,浏览器关闭后就消失了,其存在时间是短 ...

  6. 在使用 vscode 时 eslint 检测 .vue 文件中的less 部分内容

    问题: 在使用 vscode 以及 eslint 来检测 基于 webpack 的 vue-cli 的项目中,eslint 无法检测到 .vue 文件中的less 部分内容. 解答: 1.通过 下载 ...

  7. angular 中父元素ng-repeat后子元素ng-click失效

    在angular中使用ng-repeat后ng-click失效,今天在这个上面踩坑了.特此记录一下. 因为ng-repeat创造了新的SCOPE.如果要使用这个scope的话就必须使用$parent来 ...

  8. angular中的compile和link函数

    angular中的compile和link函数 前言 这篇文章,我们将通过一个实例来了解 Angular 的 directives (指令)是如何处理的.Angular 是如何在 HTML 中找到这些 ...

  9. Deferred在jQuery和Angular中的使用与简单实现

    Deferred在jQuery和Angular中的使用与简单实现 Deferred是在jQuery1.5版本中加入的,并且jQuery使用它完全重写了AJax,以前也只是偶尔使用.但是上次在使用Ang ...

随机推荐

  1. myeclipse 10激活,本人已测试过可行

    激活步骤: 下载myeclipse 10硬解程序包: ed2k://|file|%5Bmyeclipse.10.0.%E6%9B%B4%E6%96%B0%E5%8F%91%E5%B8%83%28%E7 ...

  2. ubuntu16.04安装virtualbox

    download:download.virtualbox.org/virtualbox/5.0.10/virtualbox-5.0_5.0.10-104061~Ubuntu~trusty_amd64. ...

  3. Python3 enumerate() 函数

    Python3 enumerate() 函数  Python3 内置函数 描述 enumerate() 函数用于将一个可遍历的数据对象(如列表.元组或字符串)组合为一个索引序列,同时列出数据和数据下标 ...

  4. tf.get_variable()

    1. tf.Variable()W = tf.Variable(<initial-value>, name=<optional-name>)1用于生成一个初始值为initial ...

  5. mybatis框架入门程序:演示通过mybatis实现数据库的查询操作

    我们现在工程基于的数据库见“https://www.cnblogs.com/wyhluckdog/p/10147754.html”这篇博文. 1.mybatis下载 mybatis的代码由githua ...

  6. C#设计模式之简单工厂模式(过渡模式)

    一.引言 之所以写这个系列,是了为了自己更好的理解设计模式,也为新手提供一些帮助,我都是用最简单的.最生活化的实例来说明.在上一篇文章中讲解了单例模式,今天就给大家讲一个比较简单的模式——简单工厂模式 ...

  7. PAT 1048 数字加密(20)(代码+思路)

    1048 数字加密(20)(20 分) 本题要求实现一种数字加密方法.首先固定一个加密用正整数A,对任一正整数B,将其每1位数字与A的对应位置上的数字进行以下运算:对奇数位,对应位的数字相加后对13取 ...

  8. 765A Neverending competitions

    A. Neverending competitions time limit per test 2 seconds memory limit per test 512 megabytes input ...

  9. LINUX 笔记5

    配置环境变量:(只是在当前命令行窗口中有用) 单独查看PATH环境变量,可用: [root@localhost u-boot-sh4]#echo $PATH 添加PATH环境变量,可用: [root@ ...

  10. 解决Axure发布分享预览的3个方法

    公司的同事制作的一个产品原型,要发给我,我当时正在客户这里,电脑上并没有Axure,客户又催得急,感到一阵无奈.这次回来之后,经过一番摸索,发现还是有办法的.这里给大家分享一下Axure发布分享预览的 ...