ASP.NET MVC incorect generation url when using pag

2019-09-12 06:20发布

问题:

I have to acion

    [HttpGet]
    [Route("{forumName}", Order = 8)]
    [Route("{forumName}/Page/{page}", Order = 7)]
    [OutputCache(Duration = 30, VaryByParam = "forumName;page", Location = OutputCacheLocation.ServerAndClient)]
    public async Task<ActionResult> ShowForum(string forumName, int page = 1)

and

    [HttpGet]
    [RefreshDetectFilter]
    [Block(VisibleBlock = false)]
    [Route("~/Forums/{forum}/{topicName}", Order = 6)]
    [Route("~/Forums/{forum}/{topicName}/Page/{page}", Order = 5)]
    [OutputCache(Duration = 30, VaryByParam = "topicName;page", Location = OutputCacheLocation.ServerAndClient)]
    public async Task<ActionResult> ShowTopic(string forum, string topicName, int page = 1)

Razor

 <a href="@Url.Action("ShowForum", "Forums", new {forumName = Model.NameTranslit})" title="@Model.Name">@Model.Name</a>

and

<a href="@Url.Action("ShowTopic", "Forums", new { forum = Model.CurrentForumTranslite, topicName = Model.TitleTranslite })" title="@Model.Title">@Model.Title</a>

When I at page with example this

/Forums/Test/Page/2

Link to the sub forum I have normal link, but link to the topic I have with page

/Forums/Test/Test_Topic/Page/2

But should be

/Forums/Test/Test_Topic

How I understand. I have this bug because in my actions I have the same route parameter for page

What I should to do to fix that?

回答1:

I found how the workaround the problem

For route ShowTopic

[Route("~/Forums/{forum}/{topicName}", Order = 6)]

I added name

[Route("{forum}/{topicName}", Name = "showTopic", Order = 6)]

And for get url at topic, I'm using Url.RouteUrl

 <a href="@Url.RouteUrl("showTopic", new { forum = Model.CurrentForumTranslite, topicName = Model.TitleTranslite })" title="@Model.Title">@Model.Title</a>