如何在 ASP.NET MVC 中创建返回没有控制器引用的 URL 的路由
我有一个名为 DefaultController 的控制器。在这个控制器中,我有相当于静态页面的视图。
URL 看起来像 www.site.com/Default/PageName
是否可以创建一个将这些 URL 格式化为如下形式的路由:
www.site.com/PageName
我想避免为每个都创建控制器。另一种方法是在根目录中创建 .aspx 页面,但我可以为这些页面创建路由,即:
www.site.com/PageName.aspx 变为 www.site.com/PageName 吗?
谢谢!
I have a controller call DefaultController. Inside this controller i have views for what would be the equivalent of static pages.
The URLs look like www.site.com/Default/PageName
Is it possible to create a route that would format these URL like:
www.site.com/PageName
I want to avoid creating controllers for each of these. An alternative would be to create .aspx pages in the root but can i create routes for these pages ie:
www.site.com/PageName.aspx becomes www.site.com/PageName ?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以为
DefaultController
上的PageName
操作创建显式路由,如下所示:您必须将此路由放在默认 MVC 路由之前。这种方法的最大缺点是您必须为每个静态页面创建一个路由。
另一种方法是在默认 MVC 路由之后添加一个额外的路由:
这种方法的缺点是该规则将处理所有 URL,甚至是那些通常返回 404 的 URL。
You can create explicit route for the
PageName
action on theDefaultController
like this:You have to put this route before the default MVC route. The biggest drawback for this approach is that you have to create one route per static page.
An alternative approach would be to add an additional route after the default MVC route:
The drawback for this approach is that this rule would be handling all the URLs, even those that would normally return 404.
第一种方法
创建一个捕获操作的路由:
但这意味着您必须在默认控制器上创建同样多的控制器操作。
第二种方法
如果您也想避免这种情况并且只有一个控制器+操作,请以这种方式编写路线:
此路线还定义了路线约束,因此它只会捕获那些在第一个路线段中实际上有某些内容的路线。您可以定义此约束以仅捕获您需要的那些请求(即
path = "Result|Search|Whatever"
),然后您的
DefaultController
将具有如下内容:方法似乎非常可行,但我不会推荐它,因为所有逻辑都必须经过此控制器操作(对于此类请求)。最好将这些操作分成逻辑操作。那些实际上做同样事情的(这样他们就不会有一堆
switch
语句或类似的)将用单独的路由定义(如果它们不能使用单个路由来完成)。First approach
Create a route that catches actions:
But this means you'd have to create just as many controller actions on your default controller.
Second approach
If you'd like to avoid that as well and have just one controller+action instead, write a route this way:
This route also defines a route constraint so it will catch only those routes, that actually have something in first route segment. You can define this constraint to only catch those requests that you need (ie.
path = "Result|Search|Whatever"
)then your
DefaultController
would have something like this:Second approach seems very feasible, but I wouldn't recommend it because all logic would have to go through this controller action (for these kind of requests). It would be better to separate these actions into logical ones. Those that actually do the same thing (so they wouldn't have a bunch of
switch
statements or similar) would be defined with separate routes (if they couldn't be done using a single one).