C# 在asp.net core 3中创建漂亮的url

C# 在asp.net core 3中创建漂亮的url,c#,asp.net-core,url,url-routing,asp.net-core-3.0,C#,Asp.net Core,Url,Url Routing,Asp.net Core 3.0,我想要一个如下所示的URL: 如果artCatId!=null和tagId==null: /Article/artCatId/100/pageNumber/2 或 如果artCatId==null且tagId!=空值: /Article/tagId/200/pageNumber/3 /Article/artCatId/100/tagId/200/pageNumber/3 如果阿卡提德null和tagId!=空值: /Article/tagId/200/pageNumber/3 /Arti

我想要一个如下所示的URL:

如果artCatId!=null和tagId==null:

/Article/artCatId/100/pageNumber/2

如果artCatId==null且tagId!=空值:

/Article/tagId/200/pageNumber/3
/Article/artCatId/100/tagId/200/pageNumber/3
如果阿卡提德null和tagId!=空值:

/Article/tagId/200/pageNumber/3
/Article/artCatId/100/tagId/200/pageNumber/3
如何创建这个好的URL

我在我的项目中使用了ASP.NETCore3.1

在控制器中:

public async Task<IActionResult> Index(int? artCatId = null, int? tagId = null, int pageNumber = 1)
{

}

您可以在控制器中处理所有这些

我已经在一个.net核心应用程序中完成了这项工作,并根据您的规范测试了所有URL路由

[Route("/Home/Article/ArtCatID/{artCatId:int}/TagId/{tagId:int}/PageNumber/{pageNumber:int}")]
        public IActionResult Article(int? artCatId = null, int? tagId = null, int pageNumber = 1)
        {
            //Do some Code here
            return View();
        }
        [Route("/Home/Article/ArtCatID/{artCatId:int}/PageNumber/{pageNumber:int}")]
        public IActionResult Article(int? artCatId = null, int pageNumber = 1)
        {
            //Do some Code here
            return View();
        }
        [Route("/Home/Article/TagId/{tagId:int}/PageNumber/{pageNumber:int}")]
        public IActionResult Article(int? tagId = null, int pageNumber = 1, string placeHolder = "")
        {
            //Do some Code here
            return View();
        }

这将处理上述三种情况。启动时不需要路由映射,也可以工作。您将需要三种文章方法,但在我看来,这实际上很好,因为您将根据URL获得不同的结果

一个选项是在单个方法上放置多个
RouteArribute
s:

[Route("Article/artCatID/{artCatId:int}/tagId/{tagId:int}/pageNumber/{pageNumber:int}")]
[Route("Article/artCatID/{artCatId:int}/pageNumber/{pageNumber:int}")] 
[Route("Article/tagId/{tagId:int}/pageNumber/{pageNumber:int}")] 
public IActionResult Article(int? artCatId = null, int? tagId = null, int pageNumber = 1)
{ 
   // logic to handle based on passed in values
} 

您可以组合成一个重载并启用多个路由属性,每个属性使用正确的语法指定可选值和非可选值。否则,(如果在这里进行,hrm,route)您可能需要重命名方法本身(即使用更具描述性的名称),因为mvc可能会以不明确的匹配结束,并引发异常和失败routeYou可以,但我认为看到它们扩展会有所帮助。由于URL中有硬编码的名称,我不知道它将永远无法路由,我更担心的是,如果键入的内容不正确,而不是模棱两可的匹配。所以理想情况下,我想这些URL很可能是通过编程生成的。