Asp.net-Mvc-3
Asp.net mvc 如何防止瀏覽器呼叫action方法?
我的控制器中有兩個動作(shoppingCartController)
public ActionResult Index() { //some stuff here return View(viewModel); } public ActionResult AddToCart(int id) { return RedirectToAction("Index"); }有沒有辦法阻止使用者通過在瀏覽器中輸入 url 來直接呼叫 index 操作?
例如:如果使用者瀏覽
shoppingCart/index被重定向到 Home/Index。
您可以
[ChildActionOnly]在您的操作方法上使用該屬性來確保它不會被直接呼叫,或者使用ControllerContext.IsChildAction您的操作中的屬性來確定您是否要重定向。例如:
public ActionResult Index() { if(!ControllerContext.IsChildAction) { //perform redirect here } //some stuff here return View(viewModel); }如果您不能將 Index 操作設為子操作,您可以隨時檢查引薦來源網址,了解它不是萬無一失的並且可能被欺騙。看: