3

I wanted to ask you guys if is it possible, to make some routing like this for my project /{action}/{title}?

enter image description here

I was wondering if that is possible, does this url has to be a primary key too? Since there is no ID passed to know which blog post is this.

Thank you.

Ertan Hasani
  • 797
  • 1
  • 18
  • 37

1 Answers1

6

You can do this quite easily with attribute routing:

[Route("blogs")]
public class BlogController
{
    [AcceptVerbs("GET", "HEAD", Route = "{slug}")]
    public IActionResult View(string slug)
    {
    }
}

This maps all requests to /blogs/whatever to that action, and sets slug to the value after "/blogs/".

juunas
  • 54,244
  • 13
  • 113
  • 149
  • So that means that every blogpost should have a slug column on DB to determine which is that right? – Ertan Hasani Dec 13 '17 at 11:18
  • That's what I have on my blog actually. The slug is unique per article. – juunas Dec 13 '17 at 11:19
  • Great, thank you. Also how should i handle if there are two posts with the same title? – Ertan Hasani Dec 13 '17 at 11:20
  • The slug should be unique per article. So it is up to you how you want to generate it. You can auto-generate it, but then allow the user to modify it if needed. Then if the uniqueness constraint fails in the DB, return an error in the editor that it is not unique. By the way, I also updated my answer since you might want to accept HEAD and GET requests. – juunas Dec 13 '17 at 11:23
  • Okay then. Thank you so much :) – Ertan Hasani Dec 13 '17 at 11:28