问题描述
我当前的路由类似于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();
});