【问题标题】:How do I create this route and use it?如何创建这条路线并使用它?
【发布时间】:2017-03-21 07:35:47
【问题描述】:

目前我正在使用默认路由,但我需要一个像这样工作的路由:

localhost/Admin/Users/Index
localhost/Admin/Users/Add
localhost/Admin/Users/Delete

索引添加和删除是在 AdminController.cs 中带有控制器的视图

其他地方的当前结构都很好,因为它不需要多个子目录。

目前我有我需要开始的文件:

{Project}/Views/Admin/Users/Index.cshtml

我将如何创建此路由以及如何将其应用于控制器?

我是不是在错误地处理这个问题?

【问题讨论】:

  • 好的,我在管理控制器的 Users() 操作中使用了[Route("/Users/{id?}")]。它可以工作,但是我需要明确说明我所指的视图:return View("Users/Index", model); 我试图避免必须明确说明视图。
  • [Route("/Admin/Users/Index/{id?}")] 怎么样?
  • 我相信属性路由不能以斜杠开头。
  • [Route("Admin/Users/{id?}")][Route("Admin/Users/Edit/{id?}")] 有效。至于我的目录结构,因为不是标准的,所以无法避免。介意将您的解决方案作为答案,以便我可以将其标记为未来访问者的答案吗? :)

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


【解决方案1】:

这可以使用Route attributes 轻松解决,例如:

[Route("Admin/Users/Edit/{id?}")]
public ActionResult TestView(string id)
{
    if (!string.IsNullOrEmpty(id))
    {
        return View(“OneUser”, GetUser(id));
    }
    return View(“AlUsers”, GetUsers());
}

MSDN:https://blogs.msdn.microsoft.com/webdev/2013/10/17/attribute-routing-in-asp-net-mvc-5/

【讨论】:

    【解决方案2】:

    您可以在RegisterRoutes中注册另一个指定路由路径和控制器的路由:

    routes.MapRoute(
        name: "Admin",
        url: "{controller}/Users/{action}/{id}",
        defaults: new { id = UrlParameter.Optional },
        constraints: new { controller = "Admin" }
    );
    

    要处理您的目录结构,您需要扩展默认视图引擎以添加新的视图路径:

    public class ExtendedRazorViewEngine : RazorViewEngine
    {
        public ExtendedRazorViewEngine()
        {
            List<string> existingPaths = new List<string>(ViewLocationFormats);
            existingPaths.Add("~/Views/Admin/Users/{0}.cshtml");
    
            ViewLocationFormats = existingPaths.ToArray();
        }
    }
    

    并在Application_Start注册引擎:

    protected void Application_Start()
    {
        ViewEngines.Engines.Clear();
    
        ExtendedRazorViewEngine engine = new ExtendedRazorViewEngine();
        ViewEngines.Engines.Add(engine);
    
        ...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-22
      • 2020-02-18
      • 2019-08-11
      • 2022-09-24
      • 2015-09-13
      • 1970-01-01
      • 1970-01-01
      • 2019-09-10
      相关资源
      最近更新 更多