[ASP.net Core 3.1] 資料保護Sample Code

DataProtection in Asp.net Core 

Asp.net Core就有內建,未來QueryString傳遞的參數,無須再自己手動實作加解密

1.在Startup.cs

  public void ConfigureServices(IServiceCollection services)
        {  
           //加入資料保護
            services.AddDataProtection(); 
        }

2.在Controller裡

public class DataProtectorController : Controller
{
        private readonly IDataProtector _dataProtector;

        //注入
        public DataProtectorController(IDataProtectionProvider dataProtector)
        {
            _dataProtector = dataProtector.CreateProtector("DataProtectorController");
        }

        public IActionResult Index()
        {
           
            string orderNo = Guid.NewGuid().ToString();
            ViewData["Guid"]    = orderNo;//原始值
            ViewData["OrderNo"] = _dataProtector.Protect(orderNo);//資料保護

            //限定時效
            var timeLimitedDataProtector=_dataProtector.ToTimeLimitedDataProtector();
            //設定多久後解密失效
            ViewData["LifeTimeOrderNo"] = timeLimitedDataProtector.Protect(orderNo,lifetime:new TimeSpan(0,0,5));
            return View();
        }

        public IActionResult Get(string orderNo)
        {//還原原始值
            var sourceOrderNo            = _dataProtector.Unprotect(orderNo);
            return Content(sourceOrderNo);
        }

        public IActionResult Get2(string orderNo)
        {//有時限的解密....
            var timeLimitedDataProtector =_dataProtector.ToTimeLimitedDataProtector();
            var sourceOrderNo            = timeLimitedDataProtector.Unprotect(orderNo);

            return Content(sourceOrderNo);
        }
    }