加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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

发布时间:2020-12-16 09:11:57 所属栏目:asp.Net 来源:网络整理
导读:我正在使用MVC 5 / WebApi 2和AngularJs.我想在我的视图中显示登录用户名.我知道如何使用剃刀显示该信息,但我如何使用Angular?所以基本上我需要用Angular来做这件事. span Logged In As: @Html.ActionLink(User.Identity.GetUserName(),"Manage","Account",
我正在使用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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读