【问题标题】:MVC How do I prevent calling Action Method by it's name while only allowing to call it via routingMVC 如何防止通过名称调用动作方法,而只允许通过路由调用它
【发布时间】:2016-09-08 04:54:18
【问题描述】:

我正在使用.NET4.5MVC4,并且非常广泛地使用路由。

我在名为Calculator 的操作上有默认页面路由:

context.MapRoute(
    "default",
    "Wills/{action}/{id}",
    new { controller = "Journey", action = "Calculator", id = UrlParameter.Optional }
);

要求在使用时无法调用具有操作名称 Calculator(作为 Index 页面)的 URL

http://hostname.com/controller/Calculator

并且只有在调用http://hostname.com/controller时才应该工作

如何防止通过名称调用 actionMethod,而只允许通过路由调用它?

【问题讨论】:

  • 是否需要在http://hostname.com/controller/Calculator 上抛出 404?
  • @Stefan 是的,它看起来不存在是理想的,但老实说,我会对部分解决方案感到满意。
  • 嗯,我不知道实现这一点的简单方法。您可以使用 ActionFilter 检查传入的 URL 字符串,如果符合您的条件,则返回 404。在此路由中,您默认使用 Calculator 操作。您可能需要考虑使用更通用的名称,以便可以进行更通用的修复,该修复也适用于其他控制器,但这可能需要大量重构。欢迎提出其他建议。
  • @Stefan 谢谢 Stefan 我喜欢你的想法,属性解决方案已经完成。

标签: c# asp.net-mvc asp.net-mvc-4 routing .net-4.5


【解决方案1】:

感谢@Stefan 的建议,如果直接调用 action,我做了会抛出 404 的 action 属性 - 可能不是最优雅的解决方案,但可以满足我的需要。

public class PreventDirectCallAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (filterContext.HttpContext.Request.RawUrl.Contains(filterContext.ActionDescriptor.ActionName))
        {
            throw new HttpException(404, "HTTP/1.1 404 Not Found");
        }

        base.OnActionExecuting(filterContext);
    }
}

用法如下:

[PreventDirectCall]
public ActionResult Calculator()
{
// your action code.
}

【讨论】:

    猜你喜欢
    • 2018-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-16
    • 2021-02-03
    • 2016-04-24
    • 2017-05-06
    • 2018-02-13
    相关资源
    最近更新 更多