【问题标题】:Dealing with multiple custom routes in MVC在 MVC 中处理多个自定义路由
【发布时间】:2016-05-02 01:34:47
【问题描述】:

我的 Home 控制器是这样设置的,根据它收到的参数进入不同的功能。
问题出在我的家庭控制器中,它将“gametwo”视为我在家庭控制器上的路由查询。

示例
mysite.com/serchsomething mysite.com/gametwo

我有正常的 routeconfig.cs 文件,只是添加了属性路由。

处理具有多个参数的路由的最佳方法是什么?这样他们就不会模棱两可或与任何其他路线崩溃?谢谢

家庭控制器

    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();
    }

路由配置

    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 }
        );
    }

【问题讨论】:

  • 你必须给你的路线一些东西来定义并使它们独一无二,例如[Route("Search/{Query}")]

标签: asp.net-mvc


【解决方案1】:

在上面试试这个

家庭控制器

  [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 }
            );

    }}

【讨论】:

    【解决方案2】:

    您是否提供了正确的控制器名称?我只是将您的网址视为

     mysite.com/gametwo
    
     but controller name as GameTwo  Pls change it as GameTwo and try again.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-04
      • 1970-01-01
      • 1970-01-01
      • 2015-12-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多