ASP.NET Core Зашифровать и расшифровать значение QueryString
У меня возникают проблемы с выяснением того, как зашифровать и расшифровать значение EmployeeID в моей строке запроса с помощью IDataProtectionProvider. Я использую ASP.NET Core 2.0 MVC и C#.
Я пытался следовать этому руководству https://www.mikesdotnetting.com/Article/295/encryption-and-decryption-in-asp-net-core но у меня возникают проблемы с пониманием, как это сделать в моем коде.
После вызова метода Create Post Action он перенаправляет пользователя в представление подтверждения, отображающее данные, которые они заполнили в форме. Значение EmployeeID в представлении подтверждения отображается в URL-адресе. Я бы хотел, чтобы значение EmployeeID было зашифровано для предотвращения подделки.
В представлении "Индекс" я хотел бы зашифровать значение EmployeeID, чтобы при наведении курсора на ссылки "Редактировать" и "Удалить" он не видел действительное значение EmployeeID.
Пожалуйста, посмотрите код, который у меня есть сейчас. Я действительно запутался в том, как это реализовать. Заранее спасибо!
модели
public class Employee
{
public int EmployeeID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int DepartmentID { get; set; }
public Department Department { get; set; }
public int AppointmentID { get; set; }
public Appointment Appointment { get; set; }
}
public class Department
{
public int DepartmentID { get; set; }
public string Name { get; set; }
public ICollection<Employee> Employees { get; set; }
}
public class Appointment
{
public int AppointmentID { get; set; }
public string TimeSlot { get; set; }
public ICollection<Employee> Employees { get; set; }
}
ViewModel
public class EmployeeFormVM
{
public int EmployeeID { get; set; }
[Required(ErrorMessage = "Please enter your First Name")]
[Display(Name = "First Name")]
[StringLength(50)]
public string FirstName { get; set; }
[Required(ErrorMessage = "Please enter your Last Name")]
[Display(Name = "Last Name")]
[StringLength(50)]
public string LastName { get; set; }
[Required(ErrorMessage = "Please select your Department")]
[Display(Name = "Department")]
public int DepartmentID { get; set; }
public IEnumerable<Department> Departments { get; set; }
[Required(ErrorMessage = "Please select your Appointment")]
[Display(Name = "Appointment")]
public int AppointmentID { get; set; }
public IEnumerable<Appointment> Appointments { get; set; }
}
EmployeesController
public class EmployeesController : Controller
{
IDataProtector _protector;
public EmployeesController(IDataProtectionProvider provider)
{
_protector = provider.CreateProtector(GetType().FullName);
}
private readonly WinTenDbContext _context;
public EmployeesController(WinTenDbContext context)
{
_context = context;
}
//// GET: Employees
//public async Task<IActionResult> Index()
//{
// var winTenDbContext = _context.Employees.Include(e => e.Appointment).Include(e => e.Department);
// return View(await winTenDbContext.ToListAsync());
//}
public async Task<IActionResult> Index(string sortOrder, string currentFilter, string searchString, int? page)
{
ViewData["CurrentSort"] = sortOrder;
ViewData["FirstNameSortParm"] = sortOrder == "fname" ? "fname_desc" : "fname";
ViewData["LastNameSortParm"] = String.IsNullOrEmpty(sortOrder) ? "lname_desc" : "";
ViewData["DeptNameSortParm"] = sortOrder == "deptname" ? "deptname_desc" : "deptname";
ViewData["DateSortParm"] = sortOrder == "time_slot" ? "time_slot_desc" : "time_slot";
if (searchString != null)
{
page = 1;
}
else
{
searchString = currentFilter;
}
ViewData["CurrentFilter"] = searchString;
var employees = from s in _context.Employees.Include(e => e.Appointment).Include(e => e.Department)
select s;
if (!String.IsNullOrEmpty(searchString))
{
employees = employees.Where(s => s.LastName.Contains(searchString)
|| s.FirstName.Contains(searchString));
}
switch (sortOrder)
{
case "fname":
employees = employees.OrderBy(s => s.FirstName);
break;
case "fname_desc":
employees = employees.OrderByDescending(s => s.FirstName);
break;
case "lname_desc":
employees = employees.OrderByDescending(s => s.LastName);
break;
case "deptname":
employees = employees.OrderBy(s => s.Department.Name);
break;
case "deptname_desc":
employees = employees.OrderByDescending(s => s.Department.Name);
break;
case "time_slot":
employees = employees.OrderBy(s => s.Appointment.AppointmentID);
break;
case "time_slot_desc":
employees = employees.OrderByDescending(s => s.Appointment.AppointmentID);
break;
default:
employees = employees.OrderBy(s => s.LastName);
break;
}
int pageSize = 10;
return View(await PaginatedList<Employee>.CreateAsync(employees.AsNoTracking(), page ?? 1, pageSize));
}
// GET: Employees/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var employee = await _context.Employees
.Include(e => e.Appointment)
.Include(e => e.Department)
.SingleOrDefaultAsync(m => m.EmployeeID == id);
if (employee == null)
{
return NotFound();
}
return View(employee);
}
// GET: Employees/Create
public IActionResult Create()
{
var departments = _context.Departments.ToList();
var appointments = _context.Appointments.Include(x => x.Employees).Where(x => !x.Employees.Any()).ToList();
var viewModel = new EmployeeFormVM
{
Departments = departments,
Appointments = appointments
};
return View(viewModel);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(EmployeeFormVM employee)
{
if (ModelState.IsValid)
{
var emp = new Employee();
{
emp.FirstName = employee.FirstName;
emp.LastName = employee.LastName;
emp.DepartmentID = employee.DepartmentID;
emp.AppointmentID = employee.AppointmentID;
}
// Query DB to check if Employee exists with same First/Last Name
Employee existingEmployee = await _context.Employees.SingleOrDefaultAsync(m => m.FirstName == employee.FirstName && m.LastName == employee.LastName);
if (existingEmployee != null)
{
// Display Error if duplicate employee
ModelState.AddModelError(string.Empty, "An employee with this name has already registered. Please contact the Service Desk for any scheduling conflicts.");
employee.Departments = _context.Departments.ToList();
//employee.Appointments = _context.Appointments.ToList();
employee.Appointments = _context.Appointments.ToList();
return View(employee);
}
// Query DB to check if appointment has already been assigned to an employee
Employee existingAppointment = await _context.Employees.SingleOrDefaultAsync(m => m.AppointmentID == employee.AppointmentID);
if (existingAppointment != null)
{
// Display error if the appointment was already chosen
ModelState.AddModelError(string.Empty, "This appointment has already been taken. Please select another timeslot.");
employee.Departments = _context.Departments.ToList();
//employee.Appointments = _context.Appointments.ToList();
employee.Appointments = _context.Appointments.ToList();
return View(employee);
}
_context.Add(emp);
await _context.SaveChangesAsync();
//return RedirectToAction(nameof(Index));
//var newlyCreatedId = emp.EmployeeID;
var newlyCreatedId = _protector.Protect(emp.EmployeeID.ToString());
return RedirectToAction(nameof(Confirmation), new { id = newlyCreatedId });
}
return View(employee);
}
// GET: Employees/Confirmation/5
public async Task<IActionResult> Confirmation(int? id)
{
if (id == null)
{
return NotFound();
}
var employee = await _context.Employees.Include(d => d.Department).Include(a => a.Appointment)
.SingleOrDefaultAsync(m => m.EmployeeID == id);
if (employee == null)
{
return NotFound();
}
return View(employee);
}
// GET: Employees/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var employeevm = new EmployeeFormVM();
{
Employee employee = await _context.Employees.SingleOrDefaultAsync(m => m.EmployeeID == id);
if (employee == null)
{
return NotFound();
}
employeevm.EmployeeID = employee.EmployeeID;
employeevm.FirstName = employee.FirstName;
employeevm.LastName = employee.LastName;
// Retrieve list of Departments
var departments = _context.Departments.ToList();
employeevm.Departments = departments;
// Set the selected department
employeevm.DepartmentID = employee.DepartmentID;
// Retrieve list of ALL Appointments
//var appointments = _context.Appointments.ToList();
// Retrieve list of OPEN Appointments ONLY
var appointments = _context.Appointments.Include(x => x.Employees).Where(x => !x.Employees.Any()).ToList();
employeevm.Appointments = appointments;
// Set the selected appointment
employeevm.AppointmentID = employee.AppointmentID;
}
return View(employeevm);
}
// POST: Employees/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(EmployeeFormVM vmEdit)
{
if (ModelState.IsValid)
{
Employee employee = _context.Employees.SingleOrDefault(e => e.EmployeeID == vmEdit.EmployeeID);
if (employee == null)
{
return NotFound();
}
employee.FirstName = vmEdit.FirstName;
employee.LastName = vmEdit.LastName;
employee.DepartmentID = vmEdit.DepartmentID;
employee.AppointmentID = vmEdit.AppointmentID;
try
{
_context.Update(employee);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!EmployeeExists(vmEdit.EmployeeID))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
return View(vmEdit);
}
// GET: Employees/Delete/5
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var employee = await _context.Employees
.Include(e => e.Appointment)
.Include(e => e.Department)
.SingleOrDefaultAsync(m => m.EmployeeID == id);
if (employee == null)
{
return NotFound();
}
return View(employee);
}
// POST: Employees/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var employee = await _context.Employees.SingleOrDefaultAsync(m => m.EmployeeID == id);
_context.Employees.Remove(employee);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
private bool EmployeeExists(int id)
{
return _context.Employees.Any(e => e.EmployeeID == id);
}
}
Индекс
<form asp-action="Index" method="get">
<div class="row">
<div class="col-md-2">
<a asp-action="Create" class="btn btn-primary">Schedule Employee</a>
</div>
<div class="col-md-10">
<input type="text" placeholder="Find by name" name="SearchString" value="@ViewData["currentFilter"]" />
<input type="submit" value="Search" class="btn btn-default" /> | <a asp-action="Index">Back to List</a>
</div>
</div>
</form>
<hr />
<table class="table">
<thead>
<tr>
<th>
<a asp-action="Index" asp-route-sortOrder="@ViewData["FirstNameSortParm"]">First Name</a>
</th>
<th>
<a asp-action="Index" asp-route-sortOrder="@ViewData["LastNameSortParm"]">Last Name</a>
</th>
<th>
<a asp-action="Index" asp-route-sortOrder="@ViewData["DeptNameSortParm"]">Department</a>
</th>
<th>
<a asp-action="Index" asp-route-sortOrder="@ViewData["DateSortParm"]">Appointment</a>
</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.FirstName)
</td>
<td>
@Html.DisplayFor(modelItem => item.LastName)
</td>
<td>
@Html.DisplayFor(modelItem => item.Department.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Appointment.TimeSlot)
</td>
<td>
<a asp-action="Edit" asp-route-id="@item.EmployeeID"><img src="~/images/Edit.png" alt="Edit User" /></a> |
<a asp-action="Delete" asp-route-id="@item.EmployeeID"><img src="~/images/Delete.png" alt="Delete User" /></a>
</td>
</tr>
}
</tbody>
</table>
@{
var prevDisabled = !Model.HasPreviousPage ? "disabled" : "";
var nextDisabled = !Model.HasNextPage ? "disabled" : "";
}
<a asp-action="Index"
asp-route-sortOrder="@ViewData["CurrentSort"]"
asp-route-page="@(Model.PageIndex - 1)"
asp-route-currentFilter="@ViewData["CurrentFilter"]"
class="btn btn-default @prevDisabled">
Previous
</a>
<a asp-action="Index"
asp-route-sortOrder="@ViewData["CurrentSort"]"
asp-route-page="@(Model.PageIndex + 1)"
asp-route-currentFilter="@ViewData["CurrentFilter"]"
class="btn btn-default @nextDisabled">
Next
</a>
Подтверждение просмотра
<div class="col-md-12">
<img src="~/images/confirm.png" />
<h2>Thank you @Html.DisplayFor(model => model.FirstName) @Html.DisplayFor(model => model.LastName)!</h2>
<p>Your <b>@Html.DisplayFor(model => model.Appointment.TimeSlot)</b> appointment has been booked. If you need to reschedule this appointment, please call the Service Desk at x1380.</p>
</div>