【问题标题】:Using Empty template Getting current user Id in asp.net MVC在asp.net MVC中使用空模板获取当前用户ID
【发布时间】:2017-11-09 02:52:15
【问题描述】:

伙计们,我有点迷路了,任何人都可以帮我解决这个问题,我无法显示当前用户从我的表登录的数据,我的表将始终返回空列表,该列表应该显示用户及其主题.

我在 (MVC) 中使用空模板我只有自己的自定义身份验证 + 角色。我使用 Int 数据类型作为用户 ID。感谢您能指导我如何处理这个问题。谢谢并提前

Nu-get 包:Install-Package Microsoft.AspNet.Identity.EntityFramework

命名空间:使用 Microsoft.AspNet.Identity;

控制器:

[Authorize(Roles = "Admin,Teacher")]
public ActionResult Index()
{
    int userId = User.Identity.GetUserId<int>();
    var subjectTeachers = db.SubjectTeachers.Where(x=>x.UserID==userId);
    return View(subjectTeachers.ToList());
}

型号:

[Key]
public int SubTech { get; set; }
[Display(Name ="SUBJECT")]
public int SubjectID { get; set; }
public virtual Subject Subjects { get; set; }
[Display(Name = "TEACHER")]
public int UserID { get; set; }
public ICollection< User> Users { get; set; }
[Display(Name = "LEVEL")]
public int LevelID { get; set; }
public ICollection< Level> Levels { get; set; }

目标:我的表格应该显示属于当前登录用户的主题+级别列表。但不幸的是现在它显示的是空列表,

【问题讨论】:

标签: asp.net-mvc nuget asp.net-identity


【解决方案1】:

伙计们,在做了一些研究后,我发现了根据用户当前登录的数据显示数据的方法,我只想分享给不知道的人,

我使用了空的 mvc 模板然后我按照这个教程链接 非常感谢他。http://www.dotnetawesome.com/2015/06/how-to-implement-custom-forms-authentication-in-aspnet-mvc.html.

我按照他的所有 4 个教程进行操作,然后将其添加到我的控制器中。 不要忘记使用以下命名空间。

using Microsoft.AspNet.Identity;

public ActionResult Index()
    {

        if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated == true)
        {
            var identity = (System.Web.HttpContext.Current.User as MyProject.MyPrincipal).Identity as MyProject.MyIdentity;
            var demo = db.SubjectTeachers.Where(x => x.UserID == identity.User.UserID).ToList();
            return View(demo);
        };
        return View();
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-02
    • 1970-01-01
    • 2012-10-20
    • 1970-01-01
    • 2022-09-24
    相关资源
    最近更新 更多