The basic URL structure of an asp.net core web app is:
However, I am building a resume application and wanted a URL structure similar to LinkedIn which is:
www.linkedin/ln/user-name
In my case, it would be:
To make this happen I created a controller named "hm," with the standard action method named "Index."
Next, in the Configure() method in Startup.cs I added the following code:
app.Use(async (context, next) =>
{
var url = context.Request.Path.Value;
// Rewrite to index
if (url.Contains("/hm/"))
{
var slug = url.Split('/');
if (slug[2] != null)
{
// rewrite and continue processing: Below is the matching url:
// /hm/slug-to-match
context.Request.Path = "/hm/index/" + slug[2];
}
}
await next();
});
Here, I get the URL path and ask if it contains the slug "/hm/." If it does, the logic splits the URL into an array of slugs, captures the segment directly after "/hm/," then adds the index action method in between /hm/ and the captured slug.
Finally, make sure to map the endpoints like the following.
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "hm",
pattern: "{controller=hm}/{action=Index}/{id?}");
});
This allows a user to type in www.example/hm/resume-name, while allowing the program to add in the index action method while hiding it from the user.