0

How do I omit the Id from the URL? Change from this URL:

https://localhost:7002/Product/109

to this instead ====>

https://localhost:7002/Product/productName

My controller is:

    [Route("/Product/{id}")]
    public IActionResult ShowProduct(int id)
    {
        var product = _productRipository.GetProductById(id);
        ViewBag.ProductGalleries = product.Product_Galleries
                                          .Select(p => p.ProductID == product.ProductID).ToList();
        ViewBag.ProductFeatures = product.Product_Features
                                         .Select(p => p.ProductID == product.ProductID).ToList();
        ViewBag.ProductVideos = product.Product_Videos
                                       .Select(p => p.ProductID == product.ProductID).ToList();
        ViewBag.ProductFiles = product.Product_Files
                                      .Select(p => p.ProductID == product.ProductID).ToList();

        if (product == null)
        {
            return NotFound();
        }

        return View(product);
    }
3
  • 1
    Create an API action (method) with parameter: productName with string type. Commented May 27, 2024 at 8:20
  • Do you want two paths? One with id and one with name? Commented May 27, 2024 at 8:31
  • No just with name Commented May 27, 2024 at 14:36

2 Answers 2

2

It looks like you'd rather identify the product on the route based on the product name, rather than the ID. I'd do something similar to:

[Route("/Product/{productName}")]
public IActionResult ShowProduct(string productName)
{
    Product? product = _productRepository.FindProductByName(productName);
    if (product == null)
    {
        return NotFound();
    }
    else
    {
        //whatever other operations you need 
        return View(product);    
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0
[Route("/Product")]
public IActionResult ShowProduct(int id)
{
            var id = User?.Claims?.FirstOrDefault(claim => claim.Type == ClaimTypes.Name)?.Value;
    var product = _productRipository.GetProductById(id);
    ViewBag.ProductGalleries=product.Product_Galleries.Select(p=>p.ProductID==product.ProductID).ToList();
    ViewBag.ProductFeatures = product.Product_Features.Select(p => p.ProductID == product.ProductID).ToList();
    ViewBag.ProductVideos = product.Product_Videos.Select(p => p.ProductID == product.ProductID).ToList();
    ViewBag.ProductFiles = product.Product_Files.Select(p => p.ProductID == product.ProductID).ToList();

    if (product == null)
    {
        return NotFound();
    }

    return View(product);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.