【问题标题】:Can't get aspnet.core server route to load with default path, when using Angular使用 Angular 时,无法使用默认路径加载 aspnet.core 服务器路由
【发布时间】:2018-05-23 23:17:09
【问题描述】:

我希望所有未被任何服务器端路由捕获的调用都加载我的 spa。所以在我的startup.cs 文件中,我有以下内容

// routes
app.UseMvc(routes =>
{
    // default goes to Home, and angular will deal with client side routing     
    routes.MapRoute(
        name: "default",
        template: "{*url}",
        defaults: new { controller = "home", action = "index" });
});

然后我有一个服务器页面,我想加载它而不在路径中添加单词“index”,所以当我转到http://localhost:5000/serverRoute 时它应该加载索引视图,但它总是试图加载我的 spa。但是,如果我将 URL 更改为 http://localhost:5000/serverRoute/index,则会加载服务器页面。

我的 ASP.net 核心控制器是这样的

[Route("[controller]/[action]")]
[ApiExplorerSettings(IgnoreApi = true)]
public class ServerRouteController : Controller
{
    /// <summary>
    /// Load default index view
    /// </summary>
    /// <returns></returns>
    public ViewResult Index()
    {
        return View();
    }
}

我做错了什么?

【问题讨论】:

  • [Route("[controller]/[action]")]?为什么控制器有一个动作参数?

标签: c# asp.net-core asp.net-core-routing


【解决方案1】:

路由模板中的控制器操作令牌不是可选的,这就是为什么在 URL 中不存在时不匹配的原因。

[Route("[controller]")]
[ApiExplorerSettings(IgnoreApi = true)]
public class ServerRouteController : Controller {
    /// <summary>
    /// Load default index view
    /// </summary>
    /// <returns></returns>
    [Route("")]         //Match /ServerRoute
    [Route("[action]")] //Match /ServerRoute/Index
    public IActionResult Index() {
        return View();
    }
}

参考Routing to Controller Actions in ASP.NET Core

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-01
    • 2017-07-27
    • 2013-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多