如何防止用户访问某些内部路由? [英] How to prevent certain internal routes from being accessed by the user?

查看:65
本文介绍了如何防止用户访问某些内部路由?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的网站路线很多.

某些路线,例如/sector-overview指向我希望用户看到的特定页面.

Some routes, e.g. /sector-overview are to a specific page that I want the user to see.

其他路线,例如/sectoroverview是一个最终呈现部分内容的动作,该部分内容包含在首页中.

Other routes, e.g. /sectoroverview are to an an action that ultimately renders a partial which is included on the homepage.

第二种方法只打算在应用程序内部进行,但是如果用户在地址栏中键入内容(这是一个容易犯的错误),则系统会将其视为有效请求并返回HTML部分的.

the second route is only meant to be internal to the application, but if the user types that into their address bar (it's an easy mistake to make), the system sees that as a valid request and it'll return the HTML partial.

可以将第二条路线重命名为/internal-sectoroverview之类的东西,但这并不能真正解决问题,只是将其隐藏.

I could rename the second route to something like /internal-sectoroverview, but this isn't really fixing the problem, just hiding it.

如果用户键入此请求,是否可以阻止我处理请求?对我来说,处理此问题的最佳方法是什么?

Is there any way for me to prevent the request from being processed if the user types this? What's the best way for me to deal with this issue?

推荐答案

您可以使用

You can block the route by using route constraints. However, in your case I would decorate your internal Action with [ChildActionOnly] like this:

[ChildActionOnly]
public ActionResult Overview()
{
    return View();
}

这样做,仅在使用@Html.Action@Html.RenderAction时才会呈现动作.如果尝试通过浏览器访问它,则会收到错误消息.

By doing this, the action will be only rendered when using @Html.Action or @Html.RenderAction. If you try to access it through a browser, you'll get an error.

更新

要返回404而不是错误,您可以在控制器上覆盖OnException方法并在那里进行处理.像这样:

To return a 404 instead of an error you can override the OnException method on the controller and handle it there. Something like this:

protected override void OnException(ExceptionContext filterContext)
{
    filterContext.ExceptionHandled = true;
    //check if filterContext.Exception was thrown by child action only (maybe by text)
    filterContext.Result = new HttpStatusCodeResult(404);
}

这篇关于如何防止用户访问某些内部路由?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆