Is this C# action method code actually firing a 301 redirect?
Asked Answered
S

1

6

Here is the code I use when someone visits a product page on my ecommerce website.

public ActionResult Details(int id, string slug)
{
    using (var productRepository = new EfProductRepository())
    {
        var product = productRepository.FindById(id);
        if (product == null) return RedirectToAction("Index", "Home");
        if (product.SeoTextSlug != slug)
            return RedirectToAction("Details", new {id = product.ProductId, slug = product.SeoTextSlug});

        var model = new ProductDetailModel();

        //Load the product information.
        model.Product.ProductId = product.ProductId;
        model.Product.CoverImagePath = product.CoverImagePath;
        model.Product.Name = product.Name;
        model.Product.Tagline = product.Tagline;
        model.Product.Price = product.Price;
        model.Product.Stock = product.Stock;
        model.Product.PieceCount = (int)product.PieceCount;
        model.Product.SKU = product.SKU;

        //Load the reviews for that product.
        if (product.Reviews.Any())
        {
            foreach (var review in product.Reviews)
            {
                model.Reviews.Add(new ReviewModel()
                {
                    ReviewId = review.ReviewId,
                    AccountId = (int)review.AccountId,
                    Content = review.Content,
                    Location = review.Location,
                    ProductId = (int)review.ProductId,
                    PublishDate = review.PublishDate,
                    ReviewRatingId = (int)review.ReviewRatingId
                });   
            }
        }

        return View(model);
    }
}

In this bit:

if (product.SeoTextSlug != slug)
    return RedirectToAction("Details", new {id = product.ProductId, slug = product.SeoTextSlug});

Am I actually firing a 301 redirect correctly?

Sure it's working as I want it to, but I want to make sure I'm returning a correct standard HTTP result so search engines properly respond to it.

Sardis answered 5/4, 2012 at 15:22 Comment(1)
You can confirm it by using the Developer tools of a browser. Go to Network and see the HTTP Requests.Slipshod
G
13

I believe that RedirectToAction returns 302 while RedirectToActionPermanent returns 301.

Geodetic answered 5/4, 2012 at 15:27 Comment(2)
So all I have to do on my end is use RedirectToActionPermanent instead, correct?Sardis
@Sergio: yes. The only condition is that you'd have to be sure that you want 301 instead of 302.Geodetic

© 2022 - 2024 — McMap. All rights reserved.