【问题标题】:ASP.NET Core Attribute Routing - Locale PrefixASP.NET Core 属性路由 - 区域设置前缀
【发布时间】:2020-10-07 19:39:19
【问题描述】:

我有以下控制器:

[Route("blog")]
[Route("{locale:regex(^(de|es|fr)$)}/blog", Order = -1)]
public class BlogController : Controller {
    [HttpGet("{id:int}.htm")]
    [HttpGet("{slug}/{id:int}.htm")]
    public IActionResult Details(string? slug, int id) {
        return View();
    }
}

现在,如果我尝试生成以下 URL:

  • @Url.Action("Details", "Blog", new { id = 1 })
  • @Url.Action("详细信息", "博客", 新 { slug = "cat-1", id = 1 })
  • @Url.Action("详细信息", "博客", new { id = 1, locale = "fr" })
  • @Url.Action("详细信息", "博客", 新 { slug = "cat-1", id = 1, locale = "fr" })

我希望得到以下结果:

  • /blog/1.htm
  • /blog/cat-1/1.htm
  • /fr/blog/1.htm
  • /fr/blog/cat-1/1.htm

但是这会返回:

  • /blog/1.htm
  • /blog/1.htm?slug=cat-1
  • /fr/blog/1.htm
  • /fr/blog/1.htm?slug=cat-1

我已尝试更改所有路由属性的顺序,但我无法让它返回所需的结果,我将不胜感激。

【问题讨论】:

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


    【解决方案1】:

    以下示例给出了预期的结果:

    public class BlogController : Controller
    {
        [Route("{locale:regex(^(de|es|fr)$)}/blog/{slug}/{id:int}.htm")]
        [Route("{locale:regex(^(de|es|fr)$)}/blog/{id:int}.htm", Order = 1)]
        [Route("blog/{slug}/{id:int}.htm", Order = 2)]
        [Route("blog/{id:int}.htm", Order = 3)]
        public IActionResult Details(string? slug, int id)
        {
            return View();
        }
    }
    

    此方法使用较早的Order 来获取更具体的路线,以便首先检查这些路线。明显的缺点是冗长,但它是基于所描述要求的有效解决方案。

    【讨论】:

      【解决方案2】:

      如果你不介意改变slug的顺序,你可以改变控制器如下:

          [Route("blog")]
          [Route("{locale:regex(^(de|es|fr)$)}/blog", Order = -1)]
          public class BlogController : Controller
          {
              [HttpGet("{id:int}.htm/{slug?}")]
              public IActionResult Details(string? slug, int id)
              {
                  return View();
              }
          }
      

      生成以下 URL:

      @Url.Action("Details", "Blog", new { id = 1 })
      @Url.Action("Details", "Blog", new { slug = "cat-1", id = 1 })
      @Url.Action("Details", "Blog", new { id = 1, locale = "fr" })
      @Url.Action("Details", "Blog", new { slug = "cat-1", id = 1, locale = "fr" })
      

      结果:

      /blog/1.htm
      /blog/1.htm/cat-1
      /fr/blog/1.htm
      /fr/blog/1.htm/cat-1
      

      【讨论】:

      • 谢谢,但是当我正在将应用程序从 ASP.NET 升级到 ASP.NET 核心时,slug 必须转到当前位置。我可以在没有语言环境前缀的情况下正常工作。
      猜你喜欢
      • 2019-10-21
      • 1970-01-01
      • 2019-09-13
      • 2015-12-21
      • 2021-09-04
      • 2020-11-30
      • 1970-01-01
      • 1970-01-01
      • 2012-02-15
      相关资源
      最近更新 更多