在MVC中处理多个自定义路由

时间:2016-05-02 01:34:48

标签: asp.net-mvc

我的家庭控制器设置如下,根据收到的参数进入不同的功能 问题在于我的家庭控制器,它对待" gametwo"作为我家庭控制器上的路线查询。

实施例
mysite.com/serchsomething< - 这将搜索给定的字符串
mysite.com/gametwo< - 这也是搜索而不是去gametwo控制器

我有正常的routeconfig.cs文件,只添加了attributeroutes。

处理具有多个参数的路线的最佳方法是什么?这样他们就不会有任何其他路线的暧昧或崩溃?感谢

家庭控制器

    public ActionResult Index()
    {
        ...
    }

    [HttpGet]
    [Route("{Query}")]
    public ActionResult Index(string Query)
    {
        ...
    }

    [HttpGet]
    [Route("{Query}/{Version}")]
    public ActionResult Index(string Query, int Version)
    {
        ...
    }

GameTwo控制器

    [Route("GameTwo")]
    public ActionResult Index()
    {
        return View();
    }

routeconfig

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

        routes.MapMvcAttributeRoutes();

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

2 个答案:

答案 0 :(得分:0)

您是否提供了正确的控制器名称?我只是看到你的网址

 mysite.com/gametwo

 but controller name as GameTwo  Pls change it as GameTwo and try again.

答案 1 :(得分:0)

试试以上

家庭控制器

  [HttpGet]        
        public ActionResult serchsomething(string Query)
        {
//do something
        }

游戏二控制器

      public ActionResult Index()
    {
        return View();
    }

路由

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

        /*serchsomething  action*/
                routes.MapRoute(
                    name: "Your route name 1",
                    url: "serchsomething/{Query}",
                    defaults: new
                    {
                        controller = "home",
                        action = "serchsomething"
                    }
                 );

                /*GameTwo Controller*/
                routes.MapRoute(
                   name: "Your route name 2",
                   url: "GameTwo",
                   defaults: new
                   {
                       controller = "GameTwo",
                       action = "Index"
                   }
                );
    /* default*/
            routes.MapRoute(
                  name: "Default",
                  url: "{controller}/{action}/{id}",
                  defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );

    }}