[英]How can I encode an id in url in ActionResult in asp.net mvc
我需要在返回視圖之前對id進行編碼。 在url中傳遞時可以很容易地猜到id,所以我在View中返回之前嘗試編碼
[HttpGet]
public ActionResult Index(int id = 0)
{
var model = new ReviewModel();
if (id != 0)
{
model.Id = id;
model = model.Get();
//How can I encode model.Id here***
}
ViewBag.IsAdmin = model.IsAdmin(User.Identity.Name);
model.SaveAudit("Visits Code of Conduct", User.Identity.Name);
return View(model);
}
考慮非整數標識符或手動加密/解密
由於它是一個整數,如果你想考慮將它存儲在你的模型上,那么你嘗試編碼它的選項會相當有限。 如果你能夠存儲某種類型的更多唯一標識符,例如Guid
,那么這可能是更好的,因為它會取出試圖“猜測”或改變該值的用戶的元素。
我想你可以根據你的整數值創建一些類型的哈希並傳遞它(你需要相應地更新你的值),然后解密請求的POST
端的哈希值, 類似於這個線程中提到的方法 。
可能是臨時存儲使用情況
一個考慮因素可能是使用某種形式的臨時存儲(如TempData
來存儲該值,以便在后續請求中可用:
if (id != 0)
{
model.Id = id;
model = model.Get();
// Store the ID in TempData
TempData["CurrentReviewID"] = id;
}
然后,當您的下一個請求(可能是觸發此功能的POST
被觸發時,您可以從TempData
集合中讀取您的值並使用它:
[HttpPost]
public ActionResult Index(ReviewModel model)
{
// Resolve your ID here
int int = Convert.ToInt32(TempData["CurrentReviewID"]);
// Continue as expected
}
像這樣的方法或吞噬 Session
可以用來在請求之間保留這種信息,但這可以為你的應用程序添加一個有狀態元素,你通常希望在MVC應用程序中避免這種元素。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.