简体   繁体   中英

Meaningful URL routing in ASP.NET CORE

I'm trying to figure out a better way to generate the names of products in the URL. So instead of products being represented by their Id, I'd like the name of the products.

For example: https://localhost:44233/Products/Detail/Apples

instead of

https://localhost:44233/Products/Detail/2

So far, I've changed my routing template in my StartUp.cs file from the default to the one I've posted below. It has not worked out.

Any suggestions on how to fix this would help!

StartUp.cs

app.UseMvc(routes =>
{
routes.MapRoute(
    name: "Products",
    template: "{controller=Products}/{action=Detail}/{name}"
);
});

Model

public class ProduceDetailVM
{
  public int Id {get; set;}
  public string ProduceName {get;set;}
  public string ProducePrice {get;set;}
  public string ProduceDescription {get;set;}
}

Products Controller

public async Task<IActionResult> Detail(int Id, string name)
{
  var produceDetail = repoService.GetById(Id);
  var produceName   = repoService.GetByProduceName(name);

  var produceModel = new ProduceDetailVM()
{
    Id = produceDetail.Id,
    ProduceName = produceName.Name,
    ProducePrice = produceDetail.Price,
    ProduceDescription = produceDetail.Description
};

 return View(produceModel);
}

RepoService

public class RepoService: IRepository
 {

   public ProductsTable GetById(int Id)
   {
     return _context.ProductsTable.Where(i => i.Id == Id).First();
   }

   public ProductsTable GetByProduceName(string name)
   {
     return _context.ProductsTable.Where(p => p.ProduceName == name).FirstOrDefault();
   }
}

IRepository

 public interface IRepository
{
    ProductsTable GetById(int Id);
    ProductsTable GetByProduceName(string name);
}

Detail View

<html>
    <head>
      <title>Detail Page</title>
    </head>
  <body>
    <div class="container-fluid">
        <span class="image card" style="background-image:url(produceDetail.ProductImage)"></span>
        <div class="center">
            <a class="button" asp-controller="Products" action="Detail" asp-route-id="@produceDetail.ProduceName">View More</a>
        </div>
    </div>
  </body>
</html>

So far, I've changed my routing template in my StartUp.cs

And thus totally ignored that this is like legacy technology for years now.

Attribute routing allows you to define custom routes on every action on every controller. Especially dotnet core is being ootimized for that (with the new routing engine in 2.2 that comes out this year).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM