I am developing a blog web app and I want individual blog post links to look like this: http://example.com/Post/2017/1/22/post-title
, but at the same time, if there are more than two posts in a day, the link for the second one should look like http://example.com/Post/2017/1/22/2/another-post-title
. Currently, I have it implemented following way:
[AllowAnonymous]
[Route("Post/{year:int}/{month:int}/{day:int}/{*title}")]
[HttpGet]
public Task<IActionResult> GetPostByDateTitle(int year, int month, int day, string title)
{
return this.GetPostByDate(year, month, day, 1);
}
[AllowAnonymous]
[Route("Post/{year:int}/{month:int}/{day:int}/{dayId:int}/{*title}")]
[HttpGet]
public Task<IActionResult> GetPostByDateTitle(int year, int month, int day, int dayId, string title)
{
return this.GetPostByDate(year, month, day, dayId);
}
And the Razor code:
@if (Model.DayId == 1)
{
<a asp-controller="Post" asp-action="GetPostByDateTitle" asp-route-year="@Model.Year" asp-route-month="@Model.Month" asp-route-day="@Model.Day" asp-route-title="@LinkTitle(Model.Title)">link</a>
}
else
{
<a asp-controller="Post" asp-action="GetPostByDateTitle" asp-route-year="@Model.Year" asp-route-month="@Model.Month" asp-route-day="@Model.Day" asp-route-dayid="@Model.DayId" asp-route-title="@LinkTitle(Model.Title)">link</a>
}
The title
is always ignored and exists only to make URL a bit more human readable, so it is parsed, but ignored. What I really want is to make dayId
part optional without resorting to two methods and checks in Razor code figuring out which one to call. How do I do that?