当前位置 : 主页 > 网络编程 > ASP >

asp.net-mvc – 如何使用AngularJs显示MVC登录的用户名

来源:互联网 收集:自由互联 发布时间:2021-06-24
我正在使用MVC 5 / WebApi 2和AngularJs.我想在我的视图中显示登录用户名.我知道如何使用剃刀显示该信息,但我如何使用Angular?所以基本上我需要用Angular来做这件事. span Logged In As: @Html.Act
我正在使用MVC 5 / WebApi 2和AngularJs.我想在我的视图中显示登录用户名.我知道如何使用剃刀显示该信息,但我如何使用Angular?所以基本上我需要用Angular来做这件事.

<span >Logged In As: @Html.ActionLink(User.Identity.GetUserName(), "Manage", "Account", routeValues: null, htmlAttributes: new { title = "Manage", @style = "color:white;float:right" })</span>

apiUserController

public class apiUserController : ApiController
{
    // GET api/<controller>
    public List<ApplicationUser> Get()
    {
        using (var context = new ApplicationDbContext())
        {
            List<ApplicationUser> users = new List<ApplicationUser>();
            users = context.ApplicationUsers
                .ToList();
            return users;
        }

    }
}

更新

public IHttpActionResult Get()
    {

        using (var context = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())))
        {

            var user = context.FindById(User.Identity.GetUserId());
            var loggedInUser = user.UserName;
            return Ok(loggedInUser);
        }

    }
您需要创建一个返回用户信息的服务

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

*请注意,您需要创建和端点,使用web api将用户数据作为json发送给您

一旦你完成它你就可以在任何控制器中使用它(让我们假设你有一个homecontroller,它可能是一个headercontroller或任何其他)

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

然后在你的视图中使用它,如:

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

编辑:

您建议的api控制器可能就像

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;
        }

    }

尝试阅读http://www.asp.net/web-api/overview/formats-and-model-binding/json-and-xml-serialization

用于路由尝试阅读本文(我猜你使用的是web api 2)

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

网友评论