Saving the logged-in user ID

4

I am using it in my Windows Authentication application. I have a controller where the user must register their professional experiences. However, the way the application was made, I need every time I enter a new data, put the license number or ID of it. How do I retrieve or save the perfilid (registration) that the application has already taken when opening the program so that the user does not have to type his Perfilid every time he inserts something? You need to create a session or have a simpler form.

My view looks 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; }
    
asked by anonymous 11.06.2014 / 14:27

2 answers

2

At the time of your authentication, create a Cookie or Session for save this amount. Right below the two forms of creation.

Using Cookie : stored per 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);                 
}

Retrieving Cookie:

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

Using Session : (they are stored in memory on the server, although they may vary by session state alternatives)

Creating Session

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

Recovering Session

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

You can create encryption routines to record this information.     

11.06.2014 / 16:21
0

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

So you can use it later anywhere

User.Identity.IsAuthenticated

to see if you are logged in, and

User.Identity.Name

To know the username of the logged in user

No logout to use:

FormsAuthentication.SignOut();
    
18.06.2015 / 21:14