如何将“%20”之类的Mvc路由空间更改​​为“-”

问题描述

我当前的路由类似于https://localhost:44312/Games/Sea%20of%20Thieves

我想更改为https://localhost:44312/Games/Sea-of-Thieves

我正在从事.Net Core Mvc项目。有什么想法吗?

[Route("Games/{gameName}")]
public IActionResult GameDetail(string gameName)
{
    Game requestedGame = _unitOfWork.Games.GetGameByName(gameName);
    GameDetailModel gameDetailModel = _unitOfWork.Games.GetGameDetail(requestedGame.Id,User.Identity.Name);
    return View(gameDetailModel);
}

解决方法

在网站上创建链接时,应使用-替换空格。

例如,您可以创建一个将space替换为-的接口。然后将界面插入您的视图或放置您创建的链接。

public interface IUrlHelper
{
    string RemoveSpace(string url);
}
public class UrlHelper : IUrlHelper
{
    public string RemoveSpace(string url)
    {
        return url.Replace(" ","-");
    }
}

在您看来或创建链接的任何位置,都应使用此界面

@inject IUrlHelper urlHelper
<a href="@urlHelper.RemoveSpace(YourUrl)">TestUrl</a>

注意::请记住在服务中注册IUrlHelper

,

您可以在启动配置中使用中间件

app.Use(async (context,next) =>
            {
                var url = context.Request.Path.Value;

                if (url.Contains("/Games/")&&url.Contains(" "))
                {
                    context.Response.Redirect(url.Replace(" ","-"));
                    return;
                }

                await next();
            });

结果: enter image description here

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...