没有属性路由不起作用

Routing doesn't work without attributes

编辑: An issue has been opened 在 GitHub 上用答案中的信息澄清文档。

我正在尝试在我的 .NET Core MVC 应用程序中设置路由(针对 API)。我相信我已经正确配置了所有内容,但没有路由工作(所有 return 404),除非该操作明确设置了路由属性。提到了同样的问题 here,但他不知道是什么解决了这个问题。

I put the attributes back on, it worked. I removed them, it didn't. Eventually through some magical incantation of removing and re-adding route configuration - switching it off and back on again in other words - UseMvcWithDefaultRoute() worked without routing attributes. Not sure what happened there.

这是我所拥有的简化版本。有什么问题?为什么路由在没有设置属性的情况下无法工作?

在这个例子中,我试图 POST/login/register

Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc(config =>
    {
        var policy = new AuthorizationPolicyBuilder()
                         .RequireAuthenticatedUser()
                         .Build();
        config.Filters.Add(new AuthorizeFilter(policy));
    })
        .AddJsonOptions(options =>
            options.SerializerSettings.ContractResolver = 
                new CamelCasePropertyNamesContractResolver());

public void Configure(IApplicationBuilder app,
    IHostingEnvironment env,
    ILoggerFactory loggerFactory)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseDefaultFiles();
    app.UseStaticFiles();

    app.UseMvcWithDefaultRoute();
}

我也试过手动指定路线:

app.UseMvc(routes =>
{
    routes.MapRoute(
        "default",
        "{controller=Home}/{action=Index}/{id?}");
});

登录控制器:

[Route("[controller]")]
[AllowAnonymous]
public class LoginController : Controller
{
    [HttpPost]
    [Route("register")] // only works with this here
    public IActionResult Register([FromBody]RegisterModel model)
    {
        return Ok();
    }
}

默认 {controller=Home}/{action=Index}/{id?} 路由已经将控制器和操作映射到 /Login/Controller。但是,如果您在控制器上添加 [Route] 属性,则表明您要开始构建新路由,默认路由将不再适用。因此,您要么必须从控制器和操作中删除属性,要么将其添加到两者中。您可能还想使用 [action] 路由标记:

[Route("[controller]/[action]")]
[AllowAnonymous]
public class LoginController : Controller
{
   // ...
}