简体   繁体   中英

How to get current logged in user id in ASP NET CORE 3.0?

I am a student and I am trying to learn how to use identity and relations in ASP NET, If you can just to help me where to look or what to look to learn how these work.

I am trying to make a simple todo list so the logged user has to see only own data not others, I managed to make it register, but when I want to create a todo Controller shows an error.

This problem is that when I try to get current logged in user shows me a message: *

Error

"Cannot implicitly convert type 'Microsoft.AspNetCore.Identity.IdentityUser' to 'ToDoList.Models.MyUser'. )"

Model

namespace ToDoList.Models
{
    public class MyUser : IdentityUser
    {
        public string HomeTown { get; set; }
        public virtual ICollection<ToDo> ToDoes { get; set; }
    }

    public class ToDo
    {
        public int Id { get; set; }
        public string Description { get; set; }
        public bool IsDone { get; set; }
        public virtual MyUser User { get; set; }
    }
}

Controller

 [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("Id,Description,IsDone")] ToDo toDo)
        {
            var user = await _userManager.GetUserAsync(HttpContext.User);

            if (ModelState.IsValid)
            {
                toDo.User = user; < -- Here it points the error
                _context.Todoes.Add(toDo);
                await _context.SaveChangesAsync();
                return RedirectToAction("Index");
            }
            return View(toDo);
        }

In your startup file you need to configure identity with your custom user model.

services.AddDefaultIdentity(options =.....

Be sure DI UserManager like below:

private readonly UserManager<MyUser> _userManager;
public HomeController(UserManager<MyUser>)
{
    _userManager = userManager;
}

To solve this issue, you should create a MyUser and set properties for this newly created object like this :

        var user = await _userManager.GetUserAsync(HttpContext.User);

        if (ModelState.IsValid)
        {
            var newUserInfo = new ToDoList.Models.MyUser{
                 //set related properties from user to this object
                 //for example
                 UserName = user.UserName
                 //and add other properties
            };   

            toDo.User = newUserInfo ;  
            _context.Todoes.Add(toDo);
            await _context.SaveChangesAsync();
            return RedirectToAction("Index");
        }

感谢所有试图提供帮助的人,但就我而言,Majid Qafouri 的回答正是我所需要的。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM