【问题标题】:How can I change Mvc Routing spaces like "%20" to "-"如何将 Mvc 路由空间(如“%20”)更改为“-”
【发布时间】:2021-01-30 07:35:52
【问题描述】:

我当前的路由是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);
}

【问题讨论】:

  • 显示你的控制器代码

标签: asp.net-mvc asp.net-core url-routing asp.net-mvc-routing


【解决方案1】:

在您的网站上创建链接时,应将空格替换为 -。

例如,您可以创建一个将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。

【讨论】:

  • 它必须在控制器中带有空格,但在 [Route("Games/{gameName}")] 我想将空格更改为游戏名称中的“-”。
【解决方案2】:

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

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();
            });

结果:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-03
    • 2014-01-15
    • 2013-04-21
    • 2021-12-07
    相关资源
    最近更新 更多