我有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'路线已经正常工作,默认和自定义语言路由部分,但我的网址必须包含所有路由部分:controller / action / id。我只想简单地让网址对用户更具可读性。
实际上我使用'lang'作为强制性的帖子 www.mysite.xyz/sr/Post/postID - 但我希望'sr'默认为'DefaultLocalized'路线,我不必将lang设置为'sr'......
我已经尝试过其他类似问题的答案,但我没有让它发挥作用。
答案 0 :(得分:0)
您可以使用以下属性路由:
[Route("~/{cate}")]
[Route("{lang}/{cate}")]
public IActionResult Index(string lang, string cate)
{
return View();
}
这对我的网址有用:
希望这有帮助!