locked
Session Id is changed when a request is coming. RRS feed

  • Question

  • User-1992775756 posted

    hi,

    When a request is coming, every time the session id is different. For example, same web page just refresh it, the session id is different.

    So is there any way to make the id keeps same? 

    Thanks a lot.

    Tuesday, July 9, 2019 2:14 AM

Answers

  • User1034446946 posted

    https://docs.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-2.2

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, July 9, 2019 1:52 PM

All replies

  • User1120430333 posted

    UMLer

    hi,

    When a request is coming, every time the session id is different. For example, same web page just refresh it, the session id is different.

    So is there any way to make the id keeps same? 

    Thanks a lot.

    You could take the  session id and  keep it  in a hidden field in the view tied to property in a view model and using TempData. The Create and Edit ActionMethods must know about the AuthorId at all times that was passed into the controller for data persistence of the Article object logic in the PayRollDomainModel object and other logic in PayRollDM too.

    It one way of keeping something in state..

    .

    @model ArticleVM.Article
    
    <!DOCTYPE html>
    
    <style type="text/css">
        .editor-field > label {
            float: left;
            width: 150px;
        }
    
        txtbox {
            font-family: Arial, Helvetica, sans-serif;
            font-size: 12px;
            background: white;
            color: black;
            cursor: text;
            border-bottom: 1px solid #104A7B;
            border-right: 1px solid #104A7B;
            border-left: 1px solid #104A7B;
            border-top: 1px solid #104A7B;
            padding-top: 10px;
        }
    
        textarea {
            width: 500px;
            height: 75px;
        }
    </style>
    
    <html>
    <head>
        <title>Create</title>
    </head>
    
    <body>
        <h1>Article</h1>
    
        @using (Html.BeginForm())
        {
            @Html.ValidationSummary(false, "", new { @class = "text-danger" })
    
    <fieldset>
    
        <legend>Create</legend>
        @Html.HiddenFor(model => model.AuthorId)
    
        <div class="editor-field">
            @Html.Label("Title:")
            @Html.TextBoxFor(model => model.Title, new { @Cssclass = "txtbox" })
            @Html.ValidationMessageFor(model => model.Title)
        </div>
        <br />
        <div class="editor-field">
            @Html.Label("Body:")
            @Html.TextAreaFor(model => model.Body)
        </div>
        <br />
        <br />
        <p>
            <input type="submit" name="submit" value="Save" />
            <input type="submit" name="submit" value="Cancel" />
        </p>
    
    </fieldset>
        }
    
    </body>
    </html>
    
    
    using Microsoft.AspNetCore.Mvc.Rendering;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    
    namespace PublishingCompany.Models
    {
        public class PayRollVM
        {
            public class Payroll
            {
                public int PayrollId { get; set; }
                public int AuthorId { get; set; }
                public string AuthorFirstName { get; set; }
                public string AuthorLastName { get; set; }
    
                [Required(ErrorMessage = "Author is required")]
                public string AuthorTypeId { get; set; }
    
                [Required(ErrorMessage = "Salary is required")]
                public int? Salary { get; set; }
    
                public List<SelectListItem> AuthorTypes { get; set; } = new List<SelectListItem>();
    
            }
            public List<Payroll> Payrolls { get; set; } = new List<Payroll>();
        }
    }
    using Microsoft.AspNetCore.Mvc;
    using PublishingCompany.Models;
    
    namespace PublishingCompany.Controllers
    {
        public class ArticleController : Controller
        {
            private IAuthorDM _authorDM;
            private IArticleDM _articleDM;
            public ArticleController(IAuthorDM authorDM, IArticleDM articleDM)
            {
                _authorDM = authorDM;
                _articleDM = articleDM;
            }
            public IActionResult Index() 
            {
                return View(_authorDM.GetAll());
            }
            public IActionResult ArticleIndex(int id)
            {
                TempData["AuthorId"] = id;
    
                return View(_articleDM.GetArticlesByAuthorId(id));
            }
            public ActionResult Create()
            {
                return View(_articleDM.Add((int)TempData["AuthorId"]));
            }
    
            [HttpPost]
            public ActionResult Create(ArticleVM.Article  article, string submit)
            {
                TempData["AuthorId"] = article.AuthorId;
    
                if (submit == "Cancel") return RedirectToAction("ArticleIndex", new { id = (int)TempData["AuthorId"] });
    
                if (!ModelState.IsValid) return View(article);
    
                int authorid = article.AuthorId;
                    
                _articleDM.Add(article);
                return RedirectToAction("ArticleIndex", new {id = (int) TempData["AuthorId"]});
            }
            public ActionResult Edit(int id = 0)
            {
                return id == 0 ? null : View(_articleDM.Update(id));
            }
    
            [HttpPost]
            public ActionResult Edit(ArticleVM.Article article, string submit)
            {
                TempData["AuthorId"] = article.AuthorId;
    
                if (submit == "Cancel") return RedirectToAction("ArticleIndex", new { id = (int)TempData["AuthorId"] });
    
                if (!ModelState.IsValid) return View(article);
    
                _articleDM.Update(article);
                return RedirectToAction("ArticleIndex", new { id = (int)TempData["AuthorId"] });
            }
        
            public IActionResult Delete(int id = 0)
            {
                if (id > 0) _articleDM.Delete(id);
    
                return RedirectToAction("ArticleIndex", new {id = (int)TempData["AuthorId"] });
            }
    
            public ActionResult Cancel()
            {
                return RedirectToAction("Index");
            }
        }
    }
    using ServiceLayer;
    using System.Linq;
    using Entities;
    using Microsoft.AspNetCore.Mvc.Rendering;
    
    namespace PublishingCompany.Models
    {
        public class PayRollDM : IPayRollDM
        {
            private IPayRollSvc svc;
            private IAuthorSvc svcauth;
            public PayRollDM(IPayRollSvc payRollSvc, IAuthorSvc authorSvc)
            {
                svc = payRollSvc;
                svcauth = authorSvc;
            }
    
            public PayRollVM GetAll()
            {
                var vm = new PayRollVM();
    
                var dtos = svc.GetAll().ToList();
    
                vm.Payrolls.AddRange(dtos.Select(dto => new PayRollVM.Payroll()
                {
                    PayrollId = dto.PayrollId,
                    AuthorId = dto.AuthorId,
                    AuthorFirstName = dto.AuthorFirstName,
                    AuthorLastName = dto.AuthorLastName,
                    Salary = dto.Salary
                }).ToList());
    
                return vm;
            }
    
            public PayRollVM.Payroll Find(int id)
            {
                var dto = svc.Find(id);
    
                var payroll = new PayRollVM.Payroll
                {
                    PayrollId = dto.PayrollId,
                    AuthorId = dto.AuthorId,
                    AuthorFirstName = dto.AuthorFirstName,
                    AuthorLastName = dto.AuthorLastName,
                    Salary = dto.Salary
                };
    
                return payroll;
            }
            public bool BlnFindPayRollByAuthorId(int id)
            {
                bool blnflag = false;
    
                var dto = svc.FindPayRollByAuthorId(id);
    
                if (dto.PayrollId != 0)
                {
                    blnflag = true;
                }
    
                return blnflag;
            }
            public PayRollVM.Payroll Add()
            {
                return PopulateSelectedList( new PayRollVM.Payroll());
            }
    
            public void Add(PayRollVM.Payroll payroll)
            {
                var dto = new DtoPayroll
                {
                    AuthorId = int.Parse(payroll.AuthorTypeId),
                    Salary = payroll.Salary
                };
    
                svc.Add(dto);
            }
    
            public PayRollVM.Payroll Update(int id)
            {
                var dto = Find(id);
    
                var payroll = new PayRollVM.Payroll
                {
                    PayrollId = dto.PayrollId,
                    AuthorId = dto.AuthorId,
                    AuthorFirstName = dto.AuthorFirstName,
                    AuthorLastName = dto.AuthorLastName,
                    Salary = dto.Salary
                };
    
                return payroll;
            }
    
            public void Update(PayRollVM.Payroll payroll)
            {
                var dto = new DtoPayroll
                {
                    PayrollId = payroll.PayrollId,
                    AuthorId = payroll.AuthorId,
                    Salary = payroll.Salary
                };
    
                svc.Update(dto);
            }
    
            public void Delete(int id)
            {
                var dto = new DtoId
                {
                    Id = id
                };
    
                svc.Delete(dto);
            }
    
            public PayRollVM.Payroll PopulateSelectedList(PayRollVM.Payroll payroll)
            {
                var dtos = svcauth.GetAuthorTypes().ToList();
    
                payroll.AuthorTypes.AddRange(dtos.Select(dto => new SelectListItem()
                {
                    Value = dto.Value,
                    Text = dto.Text
                }).ToList());
    
                var selected = (from a in payroll.AuthorTypes.Where(a => a.Value == payroll.AuthorTypeId) select a)
                    .SingleOrDefault();
    
                if (selected != null)
                    selected.Selected = true;
    
                return payroll;
    
            }
        }
    }
    
    Tuesday, July 9, 2019 4:21 AM
  • User-1764593085 posted

    Hi UMLer,

    Do you accept the Consent Policy on your view(basically Index view) when your application is running?If not, try to accept it.

    Another workaround is to set `options.CheckConsentNeeded = context => false;` in startup.cs ConfigureServices

    services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => false; // Default is true, make it false
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

    Refer to https://stackoverflow.com/questions/49317304/asp-net-core-2-1-session

    Best Regards,

    Xing

    Tuesday, July 9, 2019 8:04 AM
  • User-1992775756 posted

    Hi UMLer,

    Do you accept the Consent Policy on your view(basically Index view) when your application is running?If not, try to accept it.

    Another workaround is to set `options.CheckConsentNeeded = context => false;` in startup.cs ConfigureServices

    services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => false; // Default is true, make it false
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

    Refer to https://stackoverflow.com/questions/49317304/asp-net-core-2-1-session

    Best Regards,

    Xing

    Thanks for telling. But it does not work.

    Tuesday, July 9, 2019 12:34 PM
  • User475983607 posted

    The Session ID will change on each response until Session is set for the current user.   

    Secondly, you have not shared your Session configuration or sample code to reproduce this issue.

    Tuesday, July 9, 2019 1:11 PM
  • User1034446946 posted

    https://docs.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-2.2

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, July 9, 2019 1:52 PM
  • User-1992775756 posted

    mgebhard

    The Session ID will change on each response until Session is set for the current user.   

    Secondly, you have not shared your Session configuration or sample code to reproduce this issue.

    This way to get session id:

    		// construction method of my controller
    		public AccountController(IAppService serviceApp,
    			IHttpContextAccessor serviceContext,
    			IHostingEnvironment serviceHostEnv)
    		{
    			this.ServiceApp = serviceApp;
    			this.ServiceContext = serviceContext;
    			this.ServiceHostEnv = serviceHostEnv;
    		}
    

    and in some methods:

    string id = ServiceContext.HttpContext.Session.Id;

    Tuesday, July 9, 2019 2:08 PM
  • User475983607 posted

    UMLer

    This way to get session id:

    		// construction method of my controller
    		public AccountController(IAppService serviceApp,
    			IHttpContextAccessor serviceContext,
    			IHostingEnvironment serviceHostEnv)
    		{
    			this.ServiceApp = serviceApp;
    			this.ServiceContext = serviceContext;
    			this.ServiceHostEnv = serviceHostEnv;
    		}

    and in some methods:

    string id = ServiceContext.HttpContext.Session.Id;

    Still, you have not shown where Session is set or the configuration. 

    The Session Id will persist once Session is created for the user.   Until then, the Session Id will change in each response.  This is by design.

    Reading the docs should help.

    https://docs.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-2.2

    Tuesday, July 9, 2019 2:11 PM
  • User-1992775756 posted

    https://docs.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-2.2

    You know what? I love you, I sooooooooooo love you.

    Tuesday, July 9, 2019 2:50 PM