- 首先,在Razor Pages Web 应用程序项目中创建一个新的文件夹,命名为 "Authentication"。
- 在 "Authentication" 文件夹中创建一个名为 "PasswordProtection.cshtml.cs" 的新类,用于处理密码保护逻辑。
- 在 "PasswordProtection.cshtml.cs" 中添加以下命名空间引用:
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
- 在 "PasswordProtection.cshtml.cs" 中定义类,该类扩展了 "PageModel" 类,并添加以下代码:
public class PasswordProtectionModel : PageModel
{
public string Password { get; set; }
public string ReturnUrl { get; set; }
private readonly ILogger _logger;
public PasswordProtectionModel(ILogger logger)
{
_logger = logger;
}
public IActionResult OnGet(string returnUrl = null)
{
ReturnUrl = returnUrl;
return Page();
}
public IActionResult OnPost()
{
if (Password != "myPassword")
{
return Page();
}
if (!string.IsNullOrEmpty(ReturnUrl))
{
return LocalRedirect(ReturnUrl);
}
else
{
return RedirectToPage("/");
}
}
}
- 创建一个名为 "PasswordProtection.cshtml" 的 Razor 页面,并将以下代码添加到 Razor 页面:
@page "/Authentication/PasswordProtection"
@model PasswordProtectionModel
- 在需要保护的 Razor 页面中添加以下代码:
@attribute [Authorize]
- 在需要保护的 Razor 页面