skip to Main Content

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


  1. You can define a route definition to get seo friendly urls like that

    Here is how you do it with attribute routing

    public class ProfileController : Controller
    {
        [Route("Profile/{userId}")]
        public ActionResult Index(string userId)
        {
            return Content("Proile for " + userId);
        }
    }
    

    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

    @page "{id:int}"
    @model ProfileModel
    @{
        ViewData["Title"] = "Profile";
    }    
    <h3>@Model.Message</h3>
    

    And in your Profile.cshtml.cs

    public class ProfileModel : PageModel
    {
        public string Message { get; set; }
    
        public void OnGet(string id)
        {
            Message = "Profile of "+ id;
        }
    }
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search