其他分享
首页 > 其他分享> > 没有属性路由不能工作

没有属性路由不能工作

作者:互联网

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

我正在尝试在.NET Core MVC应用程序(用于API)中设置路由.我相信我已经正确配置了所有内容,但是没有路由有效(所有返回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.

这是我所拥有的简化版本.有什么问题?为什么在没有设置属性的情况下路由不起作用?

在此示例中,我试图过帐到/ 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
{
   // ...
}

标签:asp-net-core,net-core,asp-net-core-mvc,c
来源: https://codeday.me/bug/20191118/2026959.html