Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the current login user name in my Script file inside my asp.net mvc

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

But it will raise the following error:- 'HttpContext' is undefined

like image 597
john Gu Avatar asked Oct 10 '12 13:10

john Gu


People also ask

How can get current user in ASP NET MVC?

If you need to get the user from within the controller, use the User property of Controller. If you need it from the view, I would populate what you specifically need in the ViewData , or you could just call User as I think it's a property of ViewPage .

How can I get current username in asp net?

To get the current logged in user at the system I use this code: string opl = System. Security. Principal.

How can get current user details in asp net core?

You can create a method to get the current user : private Task<ApplicationUser> GetCurrentUserAsync() => _userManager. GetUserAsync(HttpContext. User);


2 Answers

    @User.Identity.Name

You can directly access user identity in script section by prefixing @

    @User.FindFirst(ClaimTypes.NameIdentifier).Value

also a good option.

like image 134
user2315057 Avatar answered Oct 03 '22 04:10

user2315057


Your script is looking for a Javascript variable called HttpContext Your code should be

@HttpContext.Current.User.Identity.Name

in Razor

so the javascript becomes

 var fullurl = 'http://localhost:8080/jw/web/json/workflow/process/list?j_username=kermit&hash=9449B5ABCFA9AFDA36B801351ED3DF66&[email protected]&packageId=' + name;

You're also missing and & between the user name and packageId if you intended for them to be separate variables

Edit: based on your comment and this being inside of a js file (which I guess I missed in the OP)

Two options:

  1. Is to hold the username inside a variable on the page calling the script file. Like this:

Page

<script>
var usrName = "@HttpContext.Current.User.Identity.Name";
</script>

JS file

....&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

like image 42
Eonasdan Avatar answered Oct 03 '22 03:10

Eonasdan