【问题标题】:Changing ASP Core default route to different controller将 ASP Core 默认路由更改为不同的控制器
【发布时间】:2017-04-29 17:27:33
【问题描述】:

我无法让我的 ASP .NET Core MVC 站点路由到除 Home 之外的其他控制器。我更改了Startup中的默认路由(这是唯一的路由):

        app.UseMvc(routes =>
        {
            routes.MapRoute(name: "default", template: "{controller=profile}/{action=index}/{id?}");
        });

我的ProfileController 看起来像:

public class ProfileController : Controller
{
    [HttpGet("index")]
    public IActionResult Index() 
    {
        return View();
    }
    ...
}

但我得到的只是在导航到基本 URL 时从 Kestrel 服务器返回 404。

【问题讨论】:

  • 尝试使用ProfileIndex 而不是profileindex
  • 没有区别..
  • 是的......我发布了一个带有工作示例的答案。路由区分大小写,所以Profileprofile 是一样的。

标签: asp.net-core asp.net-core-mvc asp.net-core-1.0


【解决方案1】:

我刚刚创建了一个新项目,它对我很有效。也许你做错了什么。

这就是我所做的。

  • 新建一个asp.net core web应用项目(选择MVC模板)
  • 更新 Startup.cs 中的默认路由:

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) {
      loggerFactory.AddConsole(Configuration.GetSection("Logging"));
      loggerFactory.AddDebug();
    
      if (env.IsDevelopment()) {
        app.UseDeveloperExceptionPage();
        app.UseBrowserLink();
      } else {
        app.UseExceptionHandler("/Home/Error");
      }
    
      app.UseStaticFiles();
    
      app.UseMvc(routes => {
        routes.MapRoute(
            name: "default",
            template: "{controller=profile}/{action=index}/{id?}");
      });
    }
    
  • 创建配置文件控制器:

    public class ProfileController : Controller {
      // GET: /<controller>/
      public IActionResult Index() {
        return View();
      }
    }
    
  • 为 Profile Controller 创建索引视图:

  • 运行项目,应该会打开配置文件的索引页面。

更新:

问题在于配置文件控制器中的[HttpGet("index")]

【讨论】:

  • HttpGet 属性?!
  • 是的。如果我在我的方法上插入 [HttpGet("index")] 它会停止工作。我猜 HttpGet 是用于 Web API 而不是 MVC。如果你正在构建一个 web api 并且需要一个网页,你可以混合使用 API 和 MVC。
  • 不,我可以在其他地方使用 HttpGet 和 HttpPost 属性——我确实更喜欢它们,只是如果你使用它,似乎默认索引会被搞砸。
猜你喜欢
  • 1970-01-01
  • 2016-04-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-30
  • 1970-01-01
  • 2022-11-02
  • 2020-03-23
相关资源
最近更新 更多