How to save the logged in user ID

Asked

Viewed 3,616 times

4

I am using in my Windows Authentication application. I have a controller where the user should register their professional experiences. However, the way the application was made, I need every time I insert a new data, put the number plate or ID of it. How do I redeem or save the Perfilid (enrollment) that the application has already picked up when opening the program so that the user does not need to enter his Perfilid every time he or she enters something? You need to create a session or have a simpler way.

My view is like this:

@model Competências.Models.Experiencia

@Scripts.Render("~/bundles/validation")

@using (Ajax.BeginForm(new AjaxOptions
                {
                    InsertionMode = InsertionMode.Replace,
                    HttpMethod = "POST"
                }))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)

         <div class="col-md-4">
        <b>Id</b>
        @Html.TextBoxFor(model => model.Perfilid, new { @class = "form-control" })
        @Html.ValidationMessageFor(model => model.Perfilid)
    </div>

    </div>

       <div class="modal-body row"> 
    <div class="col-md-12">
        @Html.LabelFor(model => model.Atividades)

        @Html.TextBoxFor(model => model.Atividades, new { @class = "form-control" })
        @Html.ValidationMessageFor(model => model.Atividades)
    </div> </div>

My controller:

        public ActionResult Create()
    {
        return PartialView();
    }


    //// POST: /Experiencia/Create

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(Experiencia experiencia)
    {
        db.Experiencia.Add(experiencia);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

Models:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace Competências.Models
{
public class Experiencia
{
    public int Id { get; set; }

        [Required(ErrorMessage = "É obrigatório descrever as atividades desempenhadas na empresa")]
    [StringLength(255, ErrorMessage = "O campo atividades pode ter no máximo 255 caracteres")]
    public string Atividades { get; set; }

    public int Perfilid { get; set; }
    public virtual Perfil Perfil { get; set; }

2 answers

2

At the time of your authentication create a Cookie or Session to store this enrollment value. Just below the two ways of creation.

Using Cookie: (are stored by user on your machine)

Creating the Cookie

if (Request.Cookies.Get("id_usuario") == null)
{
    HttpCookie cookie = new HttpCookie("id_usuario");
    cookie.Path = "/";
    // valor do usuário ou qual valor deseja guardar
    cookie.Value = "1"; 
    // tempo que ele expira está 10 minutos se pode colocar mais tempo. 
    cookie.Expires = DateTime.Now.AddMinutes(10d);        
    // envia o cookie para HttpResponse, nesse momento ele criou e você pode utilizar nas diversas páginas.
    Response.Cookies.Add(cookie);                 
}

Recovering the Cookie:

if (Request.Cookies.Get("id_usuario") != null)
{
    LblIdUsuario.Text = Request.Cookies.Get("id_usuario").Value;
}

Using Session: (are stored in the server memory, although they may vary the alternatives of session status)

Creating Session

if (Session["id_usuario"] == null)
{
    Session.Timeout = 10;
    Session.Add("id_usuario", "1");                
}

Recuperating Session

if (Session["id_usuario"] != null)
{
    LblIdUsuario.Text = (string)Session["id_usuario"];
}

Obs: You can create encryption routines to record this information.

  • Right. And this session or cookie I create inside a new controller or inside the controller where I want to rescue the information, in case, Experience?

  • So: At the time you authenticate the user by windows in the same controller method you use Creating Session or Cookie. Now to recover you will in the Controller that already exists enters the method and uses the Recovering Session or Cookie, understood @Victor

  • Got it! I’ll try here and anything else I ask for help again! hahaha Thanks for the help!

  • At what point I do the attribution of what I picked up on Session with the Pk_id I want to insert?

  • @Victor in Creating Session, I see the example, and when you want to recover this value is in Recovering Session

0

Have you tried using the FormsAuthentication.SetAuthCookie(UserName, false); ?

So you can use it later anywhere

User.Identity.IsAuthenticated

to find out if you are logged in, and

User.Identity.Name

To know the name of the logged-in user

At logout use:

FormsAuthentication.SignOut();
  • Here, you can use Id instead of Username, ok ?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.