使用一个属性为控制器中的所有操作添加路由前缀

Add route prefix to all actions in controller using one attribute

这是我的控制器

public class SpecializationsController : Controller
{    
    public ActionResult Action1()
    {
        //body
    }

    public ActionResult Action2()
    {
        //body
    }

Action1 的默认 url 当然是 /Specialization/Action1。我想为控制器中的所有操作添加前缀,使我的 ulr 像 /prefix/Specialization/Action1

我尝试将 [RoutePrefix("prefix")] 添加到我的控制器,但它不起作用。我想避免为控制器中的每个操作添加 [Route] 属性。那么如何添加这个前缀呢?

您需要将路线添加到您的路线集合中,而不是使用路线属性

routes.MapRoute(
            "Route",
            "prefix/{controller}/{action}",
            new { controller = "Specializations", action = "Index" });

我会创建 Areas:

Areas are an ASP.NET MVC feature used to organize related functionality into a group as a separate namespace (for routing) and folder structure (for views). Using areas creates a hierarchy for the purpose of routing by adding another route parameter

我知道您可能认为仅使用 "prefix" 就有些矫枉过正了,但我建议采用这种方法的原因是,如果您需要添加 "prefix",那么您很可能有还需要将视图、模型等分开。