我试图阻止用户访问abc.com/Home/Index
,而我希望用户只能通过abc.com
访问主页。我使用以下代码但不起作用。
// This code restict user to access abc.com/home/index
// Only allow user to access abc.com/home
routes.MapRoute(
"OnlyAction",
"{action}",
new { controller = "Home", action = "Index" }
);
// This code does not work, I am expecting this code to allow
// user to access home only at abc.com
routes.MapRoute(
"Home",
"",
new { controller = "Home", action = "Index"}
);

答案 0 :(得分:3)
您只需忽略该网址:
Default
然后服务器将返回找不到的404而不是页面。
当然,如果您想删除整个应用程序的所有备用路径,则需要删除public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// Ignore the alternate path to the home page
routes.IgnoreRoute("Home/Index");
routes.MapRoute(
name: "Home",
url: "",
defaults: new { controller = "Home", action = "Index" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { id = UrlParameter.Optional }
);
}
}
路由的默认值,这将使它们成为必需。
/Home/
现在您无法通过<link rel="canonical" href="http://example.com/" />
访问主页(这是使用默认路由访问主页的另一条路径)。
当然,最好的选择是使用canonical tag来确保没有额外的路线可能会损害您的SEO分数。
class Application(tornado.web.Application):
def __init__(self):
handlers = [
(r"/", HomeHandler),
(r"/iq", iQHandler),
]
super(Application, self).__init__(handlers, default_handler_class=my404Handler)
class myBaseHandler(tornado.web.RequestHandler):
def write_error(self, status_code, **kwargs):
if status_code == 404:
self.render("404.html")
else:
self.render("genericerror.html")
class my404Handler(myBaseHandler):
def prepare(self):
raise tornado.web.HTTPError(404)
class HomeHandler(myBaseHandler):
def get(self):
self.render("home.html")
class iQHandler(myBaseHandler):
@tornado.gen.coroutine
def _initialize(self):
# check if proper parameters are passed
param1 = self.get_argument('media', None)
if not param1:
raise tornado.web.HTTPError(404)
try:
res = yield self._findfiles(param1)
except Exception, e:
print ("Error in _initialize() routine --> ", e)
#raise tornado.web.HTTPError(500)
raise tornado.gen.Return(res)
@tornado.gen.coroutine
def _findfiles(self, justFileName):
# find the file and lots of other processing to do
# code hidden on purpose.
raise tornado.gen.Return(strValue)
@tornado.web.asynchronous
@tornado.gen.coroutine
def get(self):
# clear browser page
# show that we are processing
response = yield self._initialize()
# clear browser page again
self.clear()
self.finish(response)
def main():
tornado.options.parse_command_line()
http_server = tornado.httpserver.HTTPServer(Application())
http_server.listen(options.port)
tornado.ioloop.IOLoop.current().start()
if __name__ == "__main__":
main()