Asp.net MVC如何从调用的操作方法prevent浏览器? [英] Asp.net mvc How to prevent browser from calling an action method?
问题描述
我有我的控制器(shoppingCartController)内的两个动作
I have two actions inside my controller (shoppingCartController)
public ActionResult Index()
{
//some stuff here
return View(viewModel);
}
public ActionResult AddToCart(int id)
{
return RedirectToAction("Index");
}
反正是有prevent通过在浏览器中键入URL直接调用索引操作?用户
Is there anyway to prevent the users from directly calling the index action by typing the url in the browser?
例如:如果用户浏览到我的购物/指数
被重定向到首页/索引
For example: If the user browses to shoppingCart/index
be redirected to Home/Index.
推荐答案
您可以使用<$c$c>[ChildActionOnly]$c$c>属性上的操作方法,以确保它不是直接调用,或使用<$c$c>ControllerContext.IsChildAction$c$c>你的行动内财产,以确定是否要重定向。
You could use the [ChildActionOnly]
attribute on your action method to make sure it's not called directly, or use the ControllerContext.IsChildAction
property inside your action to determine if you want to redirect.
例如:
public ActionResult Index()
{
if(!ControllerContext.IsChildAction)
{
//perform redirect here
}
//some stuff here
return View(viewModel);
}
如果你不能使索引操作的子操作,你总是可以检查引用,理解,它不是万无一失的,可以被欺骗。参见:
If you can't make the Index action a child action, you could always check the referrer, understanding that it's not foolproof and can be spoofed. See:
<一个href=\"http://stackoverflow.com/questions/1471188/how-do-i-get-the-referrer-url-in-an-asp-net-mvc-action\">How我会得到引荐网址在ASP.NET MVC行动?
这篇关于Asp.net MVC如何从调用的操作方法prevent浏览器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!