Asp.Net:从URL中删除操作名称 [英] Asp.Net: Removing the action name from the URL

查看:81
本文介绍了Asp.Net:从URL中删除操作名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建允许我使用的路由规则

I am trying to create a routing rule that allows me to use

http:// localhost:***** / Profile / 2

而不是

http:/ / localhost:***** / Profile / Show / 2

访问页面。我目前有一个路由规则,可以在访问页面时成功删除索引。

to access a page. I currently have a routing rule that successfully removes index when accessing a page. How do I apply the same concept to this?

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );


推荐答案

我有两个问题可以澄清您的身份试图做。因为创建自定义路由可能会带来意想不到的后果。

I have a couple of questions to clarify what you are trying to do. Because there could be some unintended consequences to creating a custom route.

1)您是否只希望将此路由应用于Profile控制器?

1) Do you only want this route to apply to the Profile controller?

尝试在默认路由之前添加此路由。

Try adding this route before the default route..

   routes.MapRoute(
        name: "Profile",
        url: "Profile/{id}",
        defaults: new { controller = "Profile", action = "Show" }

        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );

此新路线完全摆脱了Profile控制器中的Index和其他操作。该路由也仅适用于Profile控制器,因此您的其他控制器仍然可以正常工作。

This new route completely gets rid of the Index and other actions in the Profile controller. The route also only applies to the Profile controller, so your other controllers will still work fine.

您可以在 id定义中添加正则表达式,以便仅在id为数字时使用此路由。这样,您就可以再次在Profile控制器中使用其他操作。

You can add a regular expression to the "id" definition so that this route only gets used if the id is a number as follows. This would allow you to use other actions in the Profile controller again as well.

   routes.MapRoute(
        name: "Profile",
        url: "Profile/{id}",
        defaults: new { controller = "Profile", action = "Show" }
        defaults: new { id= @"\d+" }
        );

此外,最好测试各种网址以查看每个网址使用的路由的网址。转到NuGet并添加 routedebugger
软件包。您可以在 http://上获得有关如何使用它的信息。 haacked.com/archive/2008/03/13/url-routing-debugger.aspx/

Also, it would be a good idea to test various urls to see which route would be used for each of the urls. Go to NuGet and add the "routedebugger" package. You can get information on how to use it at http://haacked.com/archive/2008/03/13/url-routing-debugger.aspx/

这篇关于Asp.Net:从URL中删除操作名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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