# 二十三、性能分析（MiniProfiler）

## 关于性能分析

在 Hoa Framework 框架中，已经默认对所有的请求、调用的业务方法、数据库操作进行了完整的性能监听。主要是基于 [MiniProfiler](https://miniprofiler.com/dotnet/) 组件实现。

## 启用性能分析组件

默认情况下，Hoa Framework 框架已经启用了性能分析选项，如需自行配置，可以在 `Hoa.Web.Host.appsetting.json` 中配置即可，如：

```javascript
{
  "AppConfigOptions": {
    "EnableGlobalAuthorizationFilter": false,
    "EnableGlobalUnifiedResultFilter": false,
    "EnableCorsSupport": true,
    "EnableGlobalPerformanceAnalysis": true,  // 启用全局性能分析，设置为false，不启用
    "EnableRedisCache": false
  },
}
```

## 如何分析

当我们启动 Hoa Framework 默认启动项目 `Hoa.Web.Hoa` 时候，浏览器就会自动跳转到 `Swagger` 页面，同时左上角会自动增加一个性能分析的小UI组件，如：

![](/files/-MA07UFk1l758gePTMhl)

这个UI组件会自动监听你的所有请求、数据库操作、异常信息，提供非常直观的数据报表。其中包括请求/执行时间，调用耗时等。如：

![](/files/-MA08PE2S1pRqCMrwC1u)

通过这些时间，我们就可以去优化我们的代码，提高我们的代码质量。

## 手动分析

有时候，我们希望能够知道某一段或者某一行代码的执行时间，这时候可以手动监听，如：

```csharp
// 如：分析获取用户收据性能
using (MiniProfiler.Current.Step("InitUser"))
{
    var user = User.Get();
    user.Init();
}

// 分析访问google网站性能
var url = "https://google.com";
using (profiler.CustomTiming("http", "GET " + url))
{
    var client = new WebClient();
    var reply = client.DownloadString(url);
}

// 还可以不适用using
var url = "https://stackoverflow.com";
var html = MiniProfiler.Current.Inline(() => new WebClient().DownloadString(url), "Fetch Stack Overflow");
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://monksoul.gitbook.io/hoa/xingnengfenxi.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
