【问题标题】:Setting custom MVC routes with fixed parts使用固定部分设置自定义 MVC 路由
【发布时间】:2016-12-17 18:23:37
【问题描述】:

我有 2 个控制器:

public class HomeController : Controller
    {
        public ActionResult Index(string id) //id is category slug
        {
           if(string.IsNullOrEmpty(id))
               id = "MainCategory";
           var model = getCategoryPageModel(id);
           return View(model);
        }
    }
public class PostController : Controller
    {
        public ActionResult Index(string id) //id is post slug
        {
          var model = getPostModel(id);
          return View(model);
        }
    }

这是我的路线配置:

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

            //angular route for admin section
            routes.MapRoute(
               name: "AngularCatchAllRoute",
               url: "Admin/{*any}",
               defaults: new { controller = "Admin", action = "Index"}
               );

            //route which includes language
            routes.MapRoute(
                name: "DefaultLocalized",
                url: "{lang}/{controller}/{action}/{id}",
                constraints: new { lang = @"(\w{2})|(\w{2}-\w{2})" },   // en or en-US
                defaults: new { controller = "Home", action = "Index", id = "" }
            );

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

        }

我想要两种类型的自定义路由:

www.mysite.xyz/categoryName - 使用默认语言 ('sr') 调用 Home/Index/id www.mysite.xyz/en/categoryName - 使用语言“en”调用 Home/Index/id

www.mysite.xyz/Post/postID - 使用默认语言('sr')调用 Post/Index/id www.mysite.xyz/en/Post/postID - 使用语言“en”调用 Post/Index/id

我的 'DefaultLocalized' 路由已经可以正常工作 与默认和自定义语言路由部分,但我的 url 必须包含所有路由部分:控制器/操作/id。我只是想简化 url 以便对用户更具可读性。

实际上,我使带有“lang”的帖子成为强制性的: www.mysite.xyz/sr/Post/postID - 但我希望 'sr' 像在 'DefaultLocalized' 路由中一样默认,我不必将 lang 设置为 'sr'...

我已经尝试过其他类似问题的一些答案,但没有成功。

【问题讨论】:

标签: c# asp.net-mvc asp.net-mvc-5 asp.net-mvc-routing


【解决方案1】:

您可以使用如下属性路由:

[Route("~/{cate}")]
[Route("{lang}/{cate}")]
public IActionResult Index(string lang, string cate)
{
   return View();
}

网址对我有用:

http://[host]/Mobile

http://[host]/en/Mobile

希望对您有所帮助!

【讨论】:

猜你喜欢
  • 2014-01-08
  • 2013-01-12
  • 2013-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多