How to show MVC logged in username with AngularJs

試著忘記壹切 提交于 2019-12-05 20:15:23

you'll need to create a service that returns your user information

angular.module('app').factory('Authentication', function ($resource) {
    var resource = $resource('/user', {}, {
        query: {
            method: 'GET',
            cache: true
        }
    });
    return resource.get().$promise;
});

* note that you'll need to create and endpoint that will send you the user data as json using web api

once you got it done you'll be able to use it in any controller (let's assume you have a homecontroller, it could be a headercontroller or any other)

angular.module('app').controller('HomeController', ['$scope', 'Authentication', function ($scope, Authentication) {
    $scope.authentication = Authentication;
}]);

then use it in your view like:

<span >Logged In As: {{authentication.user.username}} </span>

EDIT:

your api controller as you suggested could be like

public HttpResponseMessage Get()
    {
        var userId = getCurrentUserId(); //something like that
        using (var context = new ApplicationDbContext())
        {
            ApplicationUser user = new ApplicationUser();
            user = context.ApplicationUsers.SingleOrDefault(x=>x.id==userId);
            return user;
        }

    }

try to read http://www.asp.net/web-api/overview/formats-and-model-binding/json-and-xml-serialization

for routing try to read this article (I guess you are using web api 2)

http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2

Chris

If you want to cheat a little, you can do this in <head> in your _Layout:

<script type="text/javascript">
    (function(myApp) {
        myApp.username = "@User.Identity.GetUserName()";
        //optional
        myApp.otherStuff = "@moreMvcStuff";
    })(window.myApp = window.myApp || {});
</script>

Then start your angular app like this:

(function (myApp) {
    "use strict";

    //var app = set up your angular app

    app.run(["$rootScope",
        function ($rootScope) {
            $rootScope.appSettings = {
                username: myApp.username
            };
        }
    ]);     

})(window.myApp = window.myApp || {});

What you are doing is creating a single value on the window called myApp (or name it whatever you like) and passing it into your IIFE. This gives you access to it inside your angular script, bot only in that on block. So if you want it to stick around, you need to put it in a service or your rootScope.

In the app.run block, you can stick it in your rootScope or wherever you want it.

Now in your views you can display it with {{appSettings.username}}.

I call this "cheating" because it's specifically for MVC or webforms and it's not the "angular way". If you ever migrated to a fully agnostic html/js client (no asp.net mvc) and web APIs, you'd need to do what is in the currently-accepted answer.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!