如何在 asp.net mvc 中的 url 中添加页面标题?

How to add page title in url in asp.net mvc?

这是控制器:

这是我的路线,我想在 id

之后添加新闻标题

例如:news/55/مایکروساوت،سروس دو

  [Route("News/{id}")]
        public ActionResult ShowNews(int id)
        {

            var news = pageRepository.GetPageById(id);
            if (news == null)
            {
                return HttpNotFound();
            }

            news.Visit += 1;
            pageRepository.UpdatePage(news);
            pageRepository.Save();

            return View(news);
        }

这是存储库页面:

   private MyCmsContext db;

    public PageRepository(MyCmsContext context)
    {
        this.db = context;
    }
    public IEnumerable<Page> GetAllPage()
    {
        return db.Pages;
    }

    public Page GetPageById(int pageId)
    {
        return db.Pages.Find(pageId);
    }

这是存储库的界面页面:

 IEnumerable<Page> GetAllPage();
    Page GetPageById(int pageId);

    bool InsertPage(Page page);
    bool UpdatePage(Page page);
    bool DeletePage(Page page);
    bool DeletePage(int pageId);
    void Save();
> [Route("News/{id}/{title}")]
>         public ActionResult ShowNews(int id,string title)
>         {
> 
>             var news = pageRepository.GetPageById(id);
>             if (news == null)
>             {
>                 return HttpNotFound();
>             }
> 
>             news.Visit += 1;
>             pageRepository.UpdatePage(news);
>             pageRepository.Save();
> 
>             return View(news);
>         }

这是在 ASP.Net Core 3.1 上测试的: 如果你想有一个漂亮的标题(例如空格被破折号代替),首先创建一个这样的扩展方法:

 namespace BulkyBook.Utility
{
   public static class CleanURLMaker
    {
        public static string CleanURL(this string url)
        {
            // ToLower() on the string thenreplaces spaces with hyphens
            string cleanURL = url.ToLower().Replace(" ", "-");

            // cleanURL = System.Text.RegularExpressions.Regex.Replace(cleanURL , @"\s", "-");
            cleanURL = cleanURL.Replace(" ", "-");
            return cleanURL;
        }
    }
}

然后在你的view.cshtml,你引用to/call你的目标的同一个地方,你必须传递你的标题,像这样,但在发送标题之前,让它干净漂亮通过您在上面创建的扩展方法:

@using BulkyBook.Utility
 <a asp-area="Customer"  asp-controller="Home" asp-action="Details" asp-route-id="@item.ID" asp-route-Title="@item.Title.CleanURL()"> Details</a>

上面的代码等于下面的代码:

<a  href="/HelloWorld/65/this-is-my.first-title"> Details</a>

最后你的 action 方法将是这样的:(注意,如果你只想要一个干净的 URL,则不需要将 Title 作为参数传递给你的 action 方法):

 [Route("HelloWorld/{id}/{Title}")]
    public async Task<IActionResult> Details(int id)
    {
       Product product =await _unitOfWork.productRepository.GetByID(id);
       return View(product);
    }

最后你的 link 将是这样的:没有人看到你的区域、控制器和 action-method 名称

~/HelloWorld/23/this-is-my.first-title

如果您想省略 'dot' 以及您的想法,从 url 开始,只需在扩展方法中替换您最喜欢的正则表达式代码即可。