ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

没有属性路由不能工作

2019-11-18 08:14:34  阅读:284  来源: 互联网

标签:asp-net-core net-core asp-net-core-mvc c


编辑: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

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有