asp.net-core - 我可以覆盖 ASP.Net Core MVC 中单个 Controller 的默认操作吗

标签 asp.net-core asp.net-core-mvc asp.net-core-2.0 asp.net-core-mvc-2.0 asp.net-core-routing

是否可以在不影响其余路由的情况下覆盖单个 Controller 的默认操作? 我目前有一个默认路由

routes.MapRoute(
    name: "Default",
    template: "{controller}/{action}",
    defaults: new { controller = "Book", action = "Index" }
);

这在一般情况下有效,但我现在想添加一个 AdminController,但我希望 AdminController 上的默认操作是用户,而不是索引。

我真的不想在这个 Controller 上使用属性路由,因为我们稍后可能会更新默认路由,我想尽可能保持集中和 DRY。我只希望 url/Admin 和/Admin/Users 路由到这个 Controller 中的用户操作。

我目前正在使用 ASP.Net Core 2.0,打算在它发布后立即迁移到 2.1。它目前在 .Net Framework 上运行,但我们希望尽快升级到 .Net Core,一旦我们可以摆脱我们目前对框架的一些依赖(不太可能是第一个版本)。

有什么建议吗?

最佳答案

虽然比使用属性路由你可以做的更密集

routes.MapRoute( 
    name: "AdminDefault", 
    template: "Admin/{action}", 
    defaults: new { controller = "Admin", action = "Users" }
);

routes.MapRoute(
    name: "Default",
    template: "{controller=Book}/{action=Index}",        
);

在 Controller 上使用属性路由

[Route("[controller]")]
public class AdminController : Controller {    
    [HttpGet]
    [Route("")]             //Match GET admin
    [Route("[action]")]     //Match Get admin/users
    public IActionResult Users() {
        return View();    
    }    
}

甚至

[Route("[controller]/{action=Users}")]
public class AdminController : Controller {    
    [HttpGet]
    public IActionResult Users() {
        return View();    
    }    
}

引用 Routing to Controller Actions in ASP.NET Core

关于asp.net-core - 我可以覆盖 ASP.Net Core MVC 中单个 Controller 的默认操作吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50529161/

相关文章:

asp.net - 将记录器注入(inject)中间件依赖项

sql-server - 在部署到 docker/linux 的 ASP.NET Core 应用程序中使用 SQL Server Always Encrypted

c# - 找不到与命令 "dotnet-/app/Build\ClearPluginAssemblies.dll"Docker 匹配的可执行文件

elasticsearch - 如何将 X.PagedList 与 ElasticSearch Nest 一起使用?

asp.net-core - 修改 MVC 6 的原始 html 输出

mysql - 在 ASP.NET Core 2.0 预览版中使用 Pomelo MySQL EF 提供程序时出错

c# - 在 ASP.NET5 控制台应用程序中使用 Startup 类

asp.net-core - 我应该从 DDD 中的存储库返回 IQueryable<T>

c# - .Net Core 在 HttpResponseMessage 中返回一个 int

c# - 如何在 ASP.NET Core 2.0 中为 IHttpcontextAccessor 使用依赖注入(inject)