Rui Ruivo

Rui Ruivo

  • NA
  • 132
  • 37.6k

Get id from current logged in user - .net core, Razor, EF core

Jul 2 2023 6:16 PM

Good morning

In my project i have a form for inserting some data in the database and i want this data to be inserted with the current user ID so that latter i can load based on the current user id .


I can get the name, in this case my email, but i want the id.

Do i need to relate my form to the current user id ? or does the framework deal with it ?
How do i get the current session user id into my form ? or simply into my database, no need to load into the form.

        .
        .
        .

        <form method="post">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
             
             <!-- <label>@User.Identity.Name</label> -->
             
            </div>
            <div class="form-group">
                <label asp-for="Entity.Title" class="control-label"></label>
                <input asp-for="Entity.Title" class="form-control" />
                <span asp-validation-for="Entity.Title" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Entity.Description" class="control-label"></label>
                <input asp-for="Entity.Description" class="form-control" />
                <span asp-validation-for="Entity.Description" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-primary" />
            </div>
        </form>

        .
        .
        .

My Model:

using Microsoft.AspNetCore.Identity;
using System.ComponentModel.DataAnnotations;

namespace HyperWeb_V3.Models
{

    public class Entity
    {
        [Key]
        public int Id { get; set; }

        [Required]
        [StringLength(100, MinimumLength = 3)]
        [RegularExpression(@"^[a-zA-Z0-9\s]*$",
            ErrorMessage = "Only alphanumeric characters and spaces are allowed.")]
        public string Title { get; set; }

        [Required]
        [StringLength(1000)]
        public string Description { get; set; }

        // Author ID - IMPORTANT
        public IdentityUser Author { get; set; }
    }

}

Maybe i can set it automaticly in the model, would be really greath, or simply get it from somewhere when pressing the submit button.

Best regards
Rui Ruivo


Answers (3)