I am trying to create user profiles based on url.
I know how to get paramaters from url like www.domain.com/profile?id=username
But I would like to keep it SEO friendly and instead get value from url format:
www.domain.com/profile/username
I am using MVC Razor from Visual Studio 2017 and disgarded MSSQL database, instead implemented MySQL with a user table.
My thoughts how it should work.
User visits web page www.domain.com/profile/user235
the server loads up the controller and gets the input “user235”
the controller sends the input to the .cshtml page and the .cshtml page performs
query to the MySQL database getting the user data array and filling the page with the data.
Is my thoughts correct? Any advice or suggestions how I should handle this?
EDIT: Found the solution at: https://learn.microsoft.com/en-us/aspnet/web-pages/overview/routing/creating-readable-urls-in-aspnet-web-pages-sites
@UrlData[0].ToString()
This will get any value after / in razor pages
example:
profile.cshtml has string username = @UrlData[0].ToString()
www.domain.com/profile/John
@UrlData[0].ToString() = “John”
If you want something like www.domain.com/profile/John/blog43
string username = @UrlData[0].ToString()
string blogid = @UrlData[1].ToString()
And with this information you can query the database to get information…
Make sure to validate the username and blog input for any kind of sql injections.
2
Answers
I think this should help you, please have a look https://blog.mariusschulz.com/2016/07/21/generating-route-urls-in-asp-net-core-mvc
You can define a route definition to get seo friendly urls like that
Here is how you do it with attribute routing
So when you user access
/yourSite/profile/scott
the Index action of Profile controller will be executed and the username value from the url (scott) will be available in the userId parameter of the action method. Here i am simply returning a string “Profile for scott”. But you can udpate it to query your database to get the corresponding record and pass that information to a view using a view model.If you are using Razor pages, you will create a Profile page and it’s model and specify the route
And in your
Profile.cshtml.cs
Like i mentioned above, i am just printing a string with the passed username from the url. But you can change it to get your data from your db table.