Is there a way to have a RoutePrefix that starts with an optional parameter?

前端 未结 4 1939
旧巷少年郎
旧巷少年郎 2020-12-20 16:26

I want to reach the Bikes controller with these URL\'s:

/bikes     // (default path for US)
/ca/bikes  // (path for Canada)

One way of achi

4条回答
  •  独厮守ぢ
    2020-12-20 17:23

    You're correct that you can't have multiple route prefixes, which means solving this particular use case is not going to be straight forward. About the best way I can think of to achieve what you want with the minimal amount of modifications to your project is to subclass your controller. For example:

    [RoutePrefix("bikes")]
    public class BikeController : Controller
    {
        ...
    }
    
    [RoutePrefix("{country}/bikes")]
    public class CountryBikeController : BikeController
    {
    }
    

    You subclassed controller will inherit all the actions from BikeController, so you don't need to redefine anything, per se. However, when it comes to generating URLs and getting them to go to the right place, you'll either need to be explicit with the controller name:

    @Url.Action("Index", "CountryBike", new { country = "us" }
    

    Or, if you're using named routes, you'll have to override your actions in your subclassed controller so you can apply new route names:

    [Route("", Name = "CountryBikeIndex")]
    public override ActionResult Index()
    {
        base.Index();
    }
    

    Also, bear in mind, that when using parameters in route prefixes, all of your actions in that controller should take the parameter:

    public ActionResult Index(string country = "us")
    {
        ...
    

提交回复
热议问题