如何在我的 asp.net mvc 中的脚本文件中获取当前登录用户名 [英] How to get the current login user name in my Script file inside my asp.net mvc
问题描述
我有一个调用 JSON API 的脚本文件,我需要在调用过程中发送当前登录用户名.我尝试了以下方法:-
I have a script file that makes a call to JSON API, and I need to send the current login username as part of the call. I tried the following :-
$(document).ready(function () {
var name = prompt("Please enter your packageid", "test");
var fullurl = 'http://localhost:8080/jw/web/json/workflow/process/list?j_username=kermit&hash=9449B5ABCFA9AFDA36B801351ED3DF66&loginAs=' + HttpContext.Current.User.Identity.Name + 'packageId=' + name;
$.ajax({
type: "GET",
url: fullurl,
dataType: "JSONP",
success: function (result) {
//code goes here
但它会引发以下错误:- 'HttpContext' is undefined
But it will raise the following error:- 'HttpContext' is undefined
推荐答案
您的脚本正在寻找一个名为 HttpContext
的 Javascript 变量,您的代码应该是
Your script is looking for a Javascript variable called HttpContext
Your code should be
@HttpContext.Current.User.Identity.Name
在剃刀中
所以 javascript 变成了
so the javascript becomes
var fullurl = 'http://localhost:8080/jw/web/json/workflow/process/list?j_username=kermit&hash=9449B5ABCFA9AFDA36B801351ED3DF66&loginAs=@HttpContext.Current.User.Identity.Name&packageId=' + name;
如果您打算将它们作为单独的变量,那么您还缺少用户名和 packageId 之间的 &
You're also missing and &
between the user name and packageId if you intended for them to be separate variables
编辑:根据您的评论,这是在 js 文件中(我想我在 OP 中错过了)
Edit: based on your comment and this being inside of a js file (which I guess I missed in the OP)
两个选项:
- 是将用户名保存在调用脚本文件的页面上的变量中.像这样:
页面
<script>
var usrName = "@HttpContext.Current.User.Identity.Name";
</script>
JS 文件
....&loginAs='+ usrName + '&packageId=' + name;
选项二是根本不包含用户名,而只是从操作中获取它.如果您要发布的页面位于同一应用程序上,这只是一个选项
Option Two is to not include the username at all and just get it from the Action. This is only an option if the page you're posting to is on the same app
这篇关于如何在我的 asp.net mvc 中的脚本文件中获取当前登录用户名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!