You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在前端获取并显示当前登录用户名?已有点击触发的GetCurrentUser函数

获取当前登录用户名并在前端展示的解决方案

嘿,我来帮你搞定这个点击按钮获取登录用户名并展示的需求~先说说你现有代码里的小问题:你把服务器端的@HttpContext.Current.User.Identity.Name直接写在客户端JavaScript函数里了,如果这段JS是在单独的.js文件中,服务器根本不会解析这段代码,最终浏览器拿到的就是字符串"@HttpContext.Current.User.Identity.Name.ToString()",而不是实际的用户名。如果是在Razor视图的<script>块里,虽然能解析,但每次点击按钮都重新赋值其实没必要,而且不够灵活。下面给你两种靠谱的实现方式:

方式一:页面渲染时注入用户名(简单直接)

这种方式适合用户名在页面加载后不会变化的场景,服务器在渲染页面时就把用户名注入到JS变量中,点击按钮直接用这个变量展示即可:

<!-- 用来展示用户名的容器 -->
<div id="userNameDisplay" style="margin-top:10px;"></div>

<!-- 你的按钮,注意type改成button(因为不需要提交表单),加个文字颜色让按钮文字可见 -->
<button type="button" onclick="GetCurrentUser()" style="margin-left:15px; margin-top:10px; margin-bottom:5px; background-color:black; color:white;">Save Selections</button>

<script>
// 服务器渲染页面时,直接把用户名赋值给全局变量
const currentUserName = '@HttpContext.Current.User.Identity.Name';

function GetCurrentUser() {
    // 将用户名展示到页面上
    const displayElement = document.getElementById('userNameDisplay');
    displayElement.textContent = `当前登录用户:${currentUserName}`;
}
</script>

方式二:AJAX异步获取用户名(更灵活)

如果你的场景需要动态获取(比如页面加载后用户身份可能切换,或者不想在页面源码中直接暴露用户名),可以写一个后端接口,然后用JS异步调用:

第一步:写后端接口

ASP.NET Web Forms 示例:

[WebMethod]
public static string GetCurrentUserName()
{
    return HttpContext.Current.User.Identity.Name;
}

ASP.NET MVC 示例:

public ActionResult GetCurrentUserName()
{
    return Content(User.Identity.Name);
}

第二步:前端JS调用接口

<div id="userNameDisplay" style="margin-top:10px;"></div>

<button type="button" onclick="GetCurrentUser()" style="margin-left:15px; margin-top:10px; margin-bottom:5px; background-color:black; color:white;">Save Selections</button>

<script>
function GetCurrentUser() {
    // 发送请求到后端接口,替换成你的实际接口路径
    fetch('/YourPageName/GetCurrentUserName')
        .then(response => {
            if (!response.ok) {
                throw new Error('请求失败');
            }
            return response.text();
        })
        .then(userName => {
            document.getElementById('userNameDisplay').textContent = `当前登录用户:${userName}`;
        })
        .catch(error => {
            console.error('获取用户名出错:', error);
            document.getElementById('userNameDisplay').textContent = '获取用户名失败,请稍后重试';
        });
}
</script>

这样修改后,点击按钮就能正确获取并展示当前登录的用户名啦~

内容的提问来源于stack exchange,提问作者rabyusbeef

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:51:45