代码之家  ›  专栏  ›  技术社区  ›  Pankaj

asp.net mvc razor c中的get-route问题#

  •  0
  • Pankaj  · 技术社区  · 7 年前

    我的代码中总共有3条路线。

    如果我用2改变1的位置,那么2开始工作,但1给出404错误。

    我在下面的代码中有什么错误吗?

    这是GET路线,工作正常。

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

    这是get route,总是给出404错误。

    routes.MapRoute(
        name: "Default1",
        url: "{Category}",
        defaults: new { 
                        controller = "Product", 
                        action = "Index", 
                        Category = UrlParameter.Optional 
                    }
    );
    

    这是邮递路线,效果很好。

    routes.MapRoute(
        name: "Default_Without_Action",
        url: "{controller}/{action}/{Category}",
        defaults: new { 
                        controller = "Product", 
                        action = "GetProducts", 
                        Category = UrlParameter.Optional 
                    }
    );
    
    2 回复  |  直到 7 年前
        1
  •  0
  •   FabianSilva    7 年前

    测试您是否放置了url:{controller}并查看此方法是否有效

    routes.MapRoute(
        name: "Default1",
        url: "{controller}",
        defaults: new { 
                        controller = "Product", 
                        action = "Index", 
                        Category = UrlParameter.Optional 
                    }
    );
    
        2
  •  0
  •   Ravindra Vairagi    7 年前

    我检查了两条路线,工作很好。

    路线图.cs

    public static void RegisterRoutes(RouteCollection routes)
            {
                routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    
    
               //Route -1
               routes.MapRoute(
               name: "Default1",
               url: "{Category}",
               defaults: new { controller = "Product", action = "Index", Category = UrlParameter.Optional }
               );
    
               //Route - 2
                routes.MapRoute(
                    name: "Default",
                    //url: "{controller}/{action}/{id}",
                    //defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
                    url: "{controller}/{action}/{Category}",
                    defaults: new { controller = "Category", action = "Index", Category = UrlParameter.Optional }
                );
            }
    

    在初始/第一次请求时,它匹配route-1并调用产品控制器的index action方法,如下图所示。原因-我们定义了控制器产品的默认参数。

    enter image description here

    如果我们从路由1中删除defaults参数,那么在初始/第一次请求时,将调用route-2url模式匹配和category controller的index action方法,reason-我们为controller category定义了defaults参数。

    只有当任何请求与注册的url模式不匹配时,浏览器才响应404错误。

    推荐文章