.net core url 链接混淆
url 上的链接 如果不想让用户知道 猜出来可以使用
IDataProtector 解决
主要方法
创建实例
_dataProtector = protectionProvider.CreateProtector(this._purposeStrings.StudentIdRouteValue);
加密
_dataProtector.Protect(id);
解密
_dataProtector.Unprotect(id);
1 /// <summary> 2 /// 数据保护 链接字段 3 /// </summary> 4 public class DataProtectionPurposeStrings 5 { 6 public readonly string StudentIdRouteValue = "StudentIdRouteValue"; 7 8 public readonly string UserIdRouteValue = "UserIdRouteValue"; 9 10 public readonly string TeacherIdRouteValue = "TeacherIdRouteValue"; 11 }
注入
builder.Services.AddSingleton<DataProtectionPurposeStrings>();
使用
1 public class HomeController : Controller 2 { 3 private readonly ILogger<HomeController> _logger; 4 private readonly IStudentRepository _studentRepository; 5 /// <summary> 6 /// 数据保护 加密解密 7 /// </summary> 8 private readonly IDataProtector _protector; 9 private readonly DataProtectionPurposeStrings _purposeStrings; 10 private readonly IHttpContextAccessor _httpContext; 11 public HomeController(ILogger<HomeController> logger, 12 IStudentRepository studentRepository, 13 IDataProtectionProvider protector, 14 DataProtectionPurposeStrings purposeStrings, 15 IHttpContextAccessor httpContext 16 ) 17 { 18 _httpContext = httpContext; 19 _logger = logger; 20 _purposeStrings = purposeStrings; 21 _studentRepository = studentRepository; 22 _protector = protector.CreateProtector(_purposeStrings.StudentIdRouteValue); 23 } 24 25 [HttpGet] 26 public IActionResult Index() 27 { 28 29 IEnumerable<Student> list = this._studentRepository.GetAll() 30 .Select(item => 31 { 32 item.EncryptedId = _protector.Protect(item.Id.ToString()); 33 return item; 34 } 35 ); 36 37 foreach (var item in list) 38 { 39 string routeLink = Url.Action("Detail", "Student", new { ID = item.EncryptedId }); 40 this._logger.Log(LogLevel.Error, routeLink); 41 } 42 43 44 return View(list); 45 } 46 47 public IActionResult Privacy() 48 { 49 return View(); 50 } 51 52 [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] 53 public IActionResult Error() 54 { 55 return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); 56 } 57 }
对url 解密
1 [HttpGet, ActionName("Detail")] 2 public async Task<IActionResult> DetailAsync(string id) 3 { 4 if (string.IsNullOrEmpty(id)) 5 { 6 ViewBag.ErrorMessage = $" 学生ID :{id} 查找不到"; 7 return View("NotFound"); 8 } 9 string unProtectResult = null; 10 try 11 { 12 unProtectResult = _dataProtector.Unprotect(id); 13 } 14 catch (Exception) 15 { 16 17 ViewBag.ErrorMessage = $" 学生ID :{id} 查找不到"; 18 return View("NotFound"); 19 } 20 Student student = await this._studentService.GetStudentByIdAsync(int.Parse(unProtectResult)); 21 return View(student); 22 }
链接 id 已经混淆了

浙公网安备 33010602011771号