如何使用 App Insights 关联前端和后端?

Posted

技术标签:

【中文标题】如何使用 App Insights 关联前端和后端?【英文标题】:How can I correlate frontend and backend using App Insights? 【发布时间】:2021-12-20 05:34:23 【问题描述】:

我有一个 ASP.NET Core Razor 应用程序,我在其中将 javascript AppInsights 组件用于 ckient 端(在 _Layout.cshtml 中配置)和用于服务器端的 nuget 包。

很遗憾,我无法将客户端的页面浏览量与服务器端的请求关联起来。此外,无论我尝试什么,应用程序地图都没有正确绘制。如您所见,它们是“断开连接的”。

我在前端尝试了以下设置,但没有运气。有什么想法吗?

disableFetchTracking: false,
enableCorsCorrelation: true,
enableRequestHeaderTracking: true,
enableResponseHeaderTracking: true,

【问题讨论】:

您是否使用在后端服务上使用的相同检测密钥来初始化 Application Insights JavaScript 客户端? 【参考方案1】:

我想通了。 documentation only 列出了自动收集的 JavaScript 依赖项下的 XMLHttpRequest 调用。

这意味着我必须像这样改变观点

// MySite.cshtml

@page
@model ...
@
    ViewData["Title"] = "My Site";

<h1>@ViewData["Title"]</h1>

<form method="post" class="mt-1">
    <button class="btn btn-primary">Do something</button>
    <input type="hidden" name="id" value="doSomething" />
</form>

// MySite.cshtml.cs

public class MySiteModel : PageModel

    // ...
    
    public void OnPost(string id)
    
        // ...
    

对于使用 AJAX 的视图,例如这样

// MySite.cshtml 

@page
@model ...
@
    ViewData["Title"] = "Exceptions";

<h1>@ViewData["Title"]</h1>

<button class="btn btn-primary" id="doSomething">Do Something</button>

@section scripts

    <script>
        $(document).click(e => 
            var id = e.target.id;
            
            if (id == "doSomething") 
                $.ajax(
                    url: '?handler=DoSomething
                );                 
            
        );
    </script>


// MySite.cshtml.cs

public MySiteModel : PageModel 

    ... 
    public void OnGetDoSomething()
    
        ...
    

现在一切看起来都应该如此

【讨论】:

以上是关于如何使用 App Insights 关联前端和后端?的主要内容,如果未能解决你的问题,请参考以下文章

uniapp怎么和后端交互

前端和后端开发有啥区别吗

前端和后端开发有啥区别吗?

thinkphp前端和后端怎么通信

如何部署分离的前端和后端?

前端和后端需要啥呀?