[英]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.Restaurant
和NewComment.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>
}
注意事項:
AddComment
具有HttpPost
屬性,則必須將其刪除。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.