Framework/ASP.NET 5.0

.NET core 5.0 MVC - Session 사용하기.

청렴결백한 만능 재주꾼 2021. 10. 8. 05:46
반응형

0. 맨 먼저 Startup.cs 설정

COnfigureService와 Configure에 각각 AddSession과 UseSession을 추가한다.

namespace EmployeeManagement
{
    public class Startup
    {
        private readonly IConfiguration _config;
    public Startup(IConfiguration config)
        {
            _config = config;
        }

        public IConfigurationRoot Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSession(options =>
            {
                options.IdleTimeout = TimeSpan.FromMinutes(20);
                options.Cookie.HttpOnly = true;
                options.Cookie.IsEssential = true;
            });

        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {

            app.UseSession();
            
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

1. 사용할 model 설정.

// models/employee.cs

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;

namespace EmployeeManagement.Models
{
    public class Employee
    {
        public int Id { get; set; }
        [NotMapped]
        public string EncryptedId { get; set; }
        [Required]
        [MaxLength(50, ErrorMessage = "Name cannot exceed 50 characters")]
        public string FirstName { get; set; }
        [Required]
        [MaxLength(50, ErrorMessage = "Name cannot exceed 50 characters")]
        public string LastName { get; set; }
        public string LoginId { get; set; }

        [DataType(DataType.Date)]
        public DateTime HireDate { get; set; }
        public string UserType { get; set; }
        [Required]
        [RegularExpression(@"^[a-zA-Z0-0_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$", 
            ErrorMessage = "Invalid Email Format")]
        [Display(Name = "Office Email")]
        public string Email { get; set; }
        [Required]
        [MinLength(8, ErrorMessage = "Password is too short")]
        [MaxLength(30, ErrorMessage = "Password is too long")]
        public string Passwd { get; set; }
        public string PhotoPath { get; set; }
    }
}

2. Helper 만들기

C#에서는 Json을 객체화(object)를 시켜서 사용하는 것 같다. 그 과정을 도와줄 Helpers.

Newtonsoft의 Json을 사용한다. 

첫번째는 Object를 Json으로 만드는 것이고

두번째는 Jsom을 Object로 만드는 것이다. 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;

namespace EmployeeManagement.Helpers
{
    public static class SessionHelper
    {
        public static void SetObjectAsJson(this ISession session, string key, object value)
        {
            session.SetString(key, JsonConvert.SerializeObject(value));
        }

        public static T GetObjectFromJson<T>(this ISession session, string key)
        {
            var value = session.GetString(key);
            return value == null ? default(T) : JsonConvert.DeserializeObject<T>(value);
        }
    }
}

 

3. Controller 적용

HttpContext를 사용하여 key와 Value로 Session을 바로 지정해줄수 있다.

SetInt32

SetString

그리고 프로퍼티를 만들어서 session화 할 수 있다.

그리고 프로퍼티의 배열도 session화 할 수 있다.

아까 만든 Helpers에 SetObjectAsJson을 사용한다.

using EmployeeManagement.Helpers;
using EmployeeManagement.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace EmployeeManagement.Controllers
{
    [Route("demo")]
    public class DemoController : Controller
    {
        [Route("")]
        [Route("index")]
        [Route("~/")]
        [AllowAnonymous]
        public IActionResult Index()
        {
            HttpContext.Session.SetInt32("age", 20);

            HttpContext.Session.SetString("username", "abc");

            Employee employee = new()
            {
                Id = 21,
                FirstName = "Jiyeon",
                LastName = "Ha",
                Email = "gkwldus@gmail.com",
                Passwd = "Asp.Net5.0"
            };
            SessionHelper.SetObjectAsJson(HttpContext.Session, "employee", employee);

            List<Employee> employees = new List<Employee>() {
                new Employee {
                    Id = 21,
                    FirstName = "Jiyeon",
                    LastName = "Ha",
                    Email = "gkwldus@gmail.com",
                    Passwd = "Asp.Net5.0"
                },
                new Employee {
                    Id = 22,
                    FirstName = "Jieun",
                    LastName = "Lee",
                    Email = "dlwlrma@gmail.com",
                    Passwd = "Asp.Net5.0"
                },
                new Employee {
                    Id = 23,
                    FirstName = "Jisoo",
                    LastName = "Park",
                    Email = "qkrwltn@gmail.com",
                    Passwd = "Asp.Net5.0"
                },
            };
            SessionHelper.SetObjectAsJson(HttpContext.Session, "employees", employees);
            return View("Index");
        }

    }
}

 

4. View를 통해 확인

@using Microsoft.AspNetCore.Http;
@using EmployeeManagement.Helpers;
@using EmployeeManagement.Models;

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>

    <h3>Session Page</h3>
    Age: @Context.Session.GetInt32("age")
    <br />
    Username: @Context.Session.GetString("username")

    <h3>Employee Info</h3>
    @{
        Employee employee = SessionHelper.GetObjectFromJson<Employee>(Context.Session, "employee");
    }
    Id: @employee.Id
    <br />
    Name: @employee.FirstName 
    <br />
    Email: @employee.Email
    <br />
    Passwd : @employee.Passwd

    <h3>Employee List</h3>
    @{
        List<Employee> employees = SessionHelper.GetObjectFromJson<List<Employee>>(Context.Session, "employees");
    }
    @foreach (var e in employees)
    {
<div>
    Id: @e.Id
    <br />
    Name: @e.FirstName
    <br />
    Email: @employee.Email
    <br />
    Passwd : @employee.Passwd
    ==================
    <br />
</div>
    }

</body>
</html>

 

5. 결과 화면

세션이 잘 전달되어 출력되는 것을 알 수 있다.

 

참고 사이트 : https://learningprogramming.net/net/asp-net-core-mvc-5/use-session-in-asp-net-core-mvc-5/

반응형