在不使用会员系统的情况下使用密码保护页面

Password protect a page without using the membership system

我有一个 ASP.NET MVC 5 网络应用程序,它运行得很好。

这是一个具有登录功能的网站,但仅供管理员使用(我)。 认证跑会员系统(Identity)就ok了

另一方面,用户(匿名用户)可以在本网站创建post。 当他们创建它时,他们会填写一个密码字段,并且此密码与 post.

相关联

目标是这个 post 只有知道相关密码的人才能编辑或删除。

没有身份验证(没有cookie),我只希望编辑和删除页面有密码保护。

问题: 如何构建我的视图和我的控制器以添加表单并在显示受保护的内容之前对其进行验证?

我在这里迷路了,我在互联网上找不到任何帮助,因为这种情况并不常见。

谢谢!

在您的编辑操作方法中添加一个名为 password 的额外参数并从用户处获取密码。然后检查密码是否正确让用户编辑 post。在 post 返回方法中再次检查密码,如果密码正确则接受编辑。考虑这个例子:

public ActionResult Edit(int id, string password)
{
     if(_myPostManager.IsValidPassword(id,password))
     {
         var post=_myPostManager.Get(id);

         return View(new EditPostViewModel
             {ID=post.ID, Content=post.Content, Password=password});
     }
     return RedirectToAction("Error");
}

[HttpPost]
public ActionResult Edit(EditPostViewModel model)
{
    if (ModelState.IsValid)
    {
        // double check password
        if(_myPostManager.IsValidPassword(model.ID,model.Password))
        {
            // save your data to DB
            return RedirectToAction("Index");
        }
    }
    return View(model);
}

视图模型:

public EditPostViewModel
{
    public int ID{get;set;}
    public string Content {get;set;}
    public string Password {get;set;}
    // your other members
} 

并查看:

@model MyNamespace.EditPostViewModel
// inside your form element add a hidden filed and put password here
@Html.HiddenFor(model=>model.Password)
// your other fields

您也可以将密码放在会话中而不是传递给查看。或加密密码并发送加密密码查看。