尝试以非授权用户身份提交表单时出现问题

问题描述 投票:0回答:3

抱歉标题,但我不知道如何用一句话解释它。我有一个表格视图:

@using (Html.BeginForm("AddComment", "Restaurants"))
{
    @Html.TextBoxFor(c => c.NewComment.Body)
    @Html.HiddenFor(m => m.Restaurant.Id)
    <button type="submit">Add comment</button>
}

和餐厅控制器中的AddComment Action:

public ActionResult AddComment(RestaurantViewModel model, Comment newComment)
{
    var userId = User.Identity.GetUserId();
    var user = _context.Users.FirstOrDefault(u => u.Id == userId);

    newComment.RestaurantId = model.Restaurant.Id;
    newComment.AuthorId = Guid.Parse(userId);
    newComment.AuthorName = user.UserName;
    newComment.DateTime = DateTime.Now;

    _context.Comments.Add(newComment);
    _context.SaveChanges();

    return RedirectToAction("Details", "Restaurants", new { id = model.Restaurant.Id});
}

我添加了授权过滤器:

filters.Add(new AuthorizeAttribute());

当我尝试将表单作为未记录的用户提交时,它会将我重定向到登录页面。如果我登录该页面,它会调用AddComment Action,但它会将参数Model.RestaurantNewComment.Body作为空值传递。如何修复它,所以当我登录时,它会将我重定向到填充TextBox的上一页或只调用AddComment但传递正确的参数值。

c# asp.net-mvc asp.net-identity
3个回答
1
投票

没有内置的方法来做到这一点。原因是,这不是“做事的方式”。如果您的表单具有安全的POST操作,请仅对相应的GET页面进行身份验证。


0
投票

尝试删除此行:

filters.Add(new AuthorizeAttribute());

并将符号[Authorize]添加到您的方法中,例如:

[Authorize]
public ActionResult AddComment(RestaurantViewModel model, Comment newComment)
{
    var userId = User.Identity.GetUserId();
    var user = _context.Users.FirstOrDefault(u => u.Id == userId);

    newComment.RestaurantId = model.Restaurant.Id;
    newComment.AuthorId = Guid.Parse(userId);
    newComment.AuthorName = user.UserName;
    newComment.DateTime = DateTime.Now;

    _context.Comments.Add(newComment);
    _context.SaveChanges();

    return RedirectToAction("Details", "Restaurants", new { id = model.Restaurant.Id});
}

0
投票

我建议不要在最简单的情况下做这件事。您可以更改表单以使用get而不是post

@using (Html.BeginForm("AddComment", "Restaurants", FormMethod.Get))
{
    @Html.TextBoxFor(c => c.NewComment.Body)
    @Html.HiddenFor(m => m.Restaurant.Id)
    <button type="submit">Add comment</button>
}

注意事项:

  • 这仅在您使用内置身份验证或您的实现转发查询字符串值时才有效。
  • 其次,值将在URL中,因此它们可以轻松地被篡改。
  • 最后,但并非最不重要的是,如果AddComment具有HttpPost属性,则必须将其删除。
© www.soinside.com 2019 - 2024. All rights reserved.