【问题标题】:C# URL RewritingC# URL 重写
【发布时间】:2019-07-14 00:23:12
【问题描述】:

我不知道做这种事情,所以很抱歉我缺乏代码示例(我一直在互联网上搜索这个主题,我似乎找不到任何我正在尝试做的事情的例子)。

我有一系列的 URL,看起来像这样:

/content/product-A/
/content/product-B/

我需要编写一个规则将它们重定向到以下内容:

/result/?product=producta
/result/?product=productb

根据我的阅读,我应该在 web.config 中的重写规则中执行此操作,但除此之外,我真的不知道如何实现(如果可能的话)。

从评论编辑:产品将类似于 my-widgetmy-super-widgetsuper-gold -widget

能否请一个更聪明的灵魂给我一些帮助?

谢谢, C

【问题讨论】:

  • 它是一个 MVC 项目吗?
  • 这是一个MVC项目是的

标签: c# url-rewriting


【解决方案1】:

在您的 content 控制器中,您可能有类似这样的内容:

     // eg: /content
    // eg: /content/product-A
    [Route("content/{productName?}")]
    public ActionResult View(string productName)
    {
        if (!String.IsNullOrEmpty(productName))
        {
            return View("ViewProduct", GetProduct(productName));
        }
        return View("AllProducts", GetProducts());
    }

此时我认为您可以重定向到 result 操作

            // eg: /content
            // eg: /content/product-A
            [Route("content/{productName?}")]
            public ActionResult View(string productName)
            {
                if (!String.IsNullOrEmpty(productName))
                {
              productName = productName.Replace("-","").ToLower();
              return RedirectToAction("result", new { product= productName  );
                }
                return View("AllProducts", GetProducts());
            }

您将需要任何配置

【讨论】:

  • 您好,感谢您的回复,对不起,我可能应该详细说明产品的名称,例如 my-widget、my-super-widget、super-gold-widget 等(我写了 product- a,product-b,以使其更易于阅读,但我现在意识到这是一个错误)。
  • 您是否需要从产品名称中删除所有“-”?
  • 我愿意,我的朋友
  • 我认为你可以通过控制器做任何事情。我编辑了我的答案
猜你喜欢
  • 2012-06-16
  • 2014-04-26
  • 1970-01-01
  • 2011-10-23
  • 2012-03-18
  • 2011-10-13
  • 2016-05-23
  • 1970-01-01
  • 2018-04-17
相关资源
最近更新 更多