Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Friendly URLs in ASP.NET MVC 6 (ASP.NET Core or ASP.NET5)

In my web site I have this kind of URLs:

https://www.mywebsite.com/View/Index/{MongoDbId}

The Controller return a View with the product details.

My product class DTO (just important fields)

public class ProductDto
{
   public string Id {get; set;}
   public string Name {get; set;}
}

In this moment I have a controller called View, and an Index method that process the request, but I would like to have something like this:

https://www.mywebsite.com/v/56b8b8801561e80c245a165c/amazing-product-name

What is the best way to implement this?

I have read about routing in ASP.NET Core (official project on GitHub), but I don't have very clear how to do.

Thanks!!

like image 814
chemitaxis Avatar asked Feb 07 '23 12:02

chemitaxis


1 Answers

To globally configure routing in ASP.NET Core, use extension method in Startup.cs:

 app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

In your case, for url: https://www.mywebsite.com/v/56b8b8801561e80c245a165c/amazing-product-name it could look like this:

 app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "v/{customId}/{customName}",
                    defaults : new{controller = "View", action = "Index"});
            });

And then your action should handle customId and customName parameters as follows:

public IActionResult Index(string customId, string customName)
{
   //customId will be 56b8b8801561e80c245a165c
   //customName will be amazing-product-name
}

For more info about routing in ASP.NET Core go to: http://docs.asp.net/en/latest/fundamentals/routing.html?highlight=routing

like image 155
Marcin Zablocki Avatar answered Feb 16 '23 04:02

Marcin Zablocki