簡體   English   中英

嘗試以未授權用戶身份提交表單時出現問題

[英]Problem when trying to submit form as a not authorized user

對不起,標題,但我不知道如何用一句話來解釋。 我對表格有看法:

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

在Restaurantss控制器中執行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為null。 如何修復它,因此在我登錄時,它會將我重定向到填充了TextBox的前一頁,或者僅調用AddComment但傳遞正確的參數值。

沒有內置的方法可以做到這一點。 原因是,這不是“做事的方式”。 如果您的表單具有受保護的POST操作,則還應使相應的GET頁面僅經過身份驗證。

嘗試刪除此行:

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});
}

我不建議在最簡單的情況下進行此操作。 您可以將表單更改為使用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屬性,則必須將其刪除。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM