我想调用控制器的默认操作。

时间:2014-07-31 12:37:21

标签: asp.net-mvc asp.net-mvc-routing

示例:我的用户将输入www.xyz.com/Promo/PROMO123

其中" PROMO123"是价值,我需要。

上面的代码会产生错误:

Server Error in '/' Application.

无法找到资源。

Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable.  Please review the following URL and make sure that it is spelled correctly.

然而  www.xyz.com/Promo/Index/PROMO123将正常运作, 但我不想要这个。

我如何存档

 www.xyz.com/Promo/PROMO123

2 个答案:

答案 0 :(得分:1)

您是否尝试过Routing

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        //Don't forget to add this before default one.
        routes.MapRoute(
            name: "PromoRoute",
            url: "{controller}/{myString}",
            defaults: new { controller = "Promo", action = "Index", myString = UrlParameter.Optional }
        );

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

答案 1 :(得分:0)

您需要为此定义路线模式。

如果您希望此应用程序在应用程序范围内工作,则需要更改默认路由。但是除了默认路由之外,我建议只为这个控制器添加一个特定的路由,因为您可能不想覆盖整个应用程序的默认MVC路由,否则您将失去使用每个操作的多个操作的能力控制器。

请参阅您的RouteConfig,尝试此路线(MVC pre-5):

 routes.MapRoute("myRoute", "PromoRoute/{id}",
                     new {controller="PromoRoute", action = "Index"});

使用MVC5,您可以直接将此添加到您的操作中,假设您已启用属性路径:

 [Route("PromoRoute/{id}")]
 public ActionResult Index(string id) {

 }
相关问题