1 回答
TA贡献1815条经验 获得超6个赞
最后我通过两种方式解决了这个问题。现在我将详细描述。
实施 UrlRules:
我写了一个继承自 IRule 的类,例如
public class UrlRules : IRule
{
public void ApplyRule(RewriteContext context)
{
var request = context.HttpContext.Request;
if (!IsValidUrl(request.Path))
{
var response = context.HttpContext.Response;
response.StatusCode = StatusCodes.Status404NotFound;
context.Result = RuleResult.EndResponse;
response.Headers[HeaderNames.Location] = "/home/error";
}
}
public bool IsValidUrl(string path)
{
bool urlValid = false;
switch (path)
{
case "/":
case "/about-us":
case "/about-us/":
case "/GetCountryInfo":
case "/pricing":
case "/pricing/":
case "/sign-in":
case "/sign-in/":
case "/sign-up":
case "/sign-up/":
urlValid = true;
break;
default:
urlValid = false;
break;
}
return urlValid;
}
}
然后像这样配置路由
app.UseMvc(routes =>
{
var rewrites = new RewriteOptions()
.Add(new UrlRules())
.AddRewrite(@"GetCountryInfo", "Home/GetCountryInfo", skipRemainingRules: true)
.AddRewrite(@"about-us", "Home/about", skipRemainingRules: true)
.AddRewrite(@"pricing", "Home/Pricing", skipRemainingRules: true)
.AddRewrite(@"sign-in", "Home/Sign_in", skipRemainingRules: true)
.AddRewrite(@"sign-up", "Home/Sign_up", skipRemainingRules: true);
app.UseRewriter(rewrites);
routes.MapRoute(
name:"default",
template: "{controller=Home}/{action=Index}/{id?}");
});
它正在工作。
定义路线:
这对我来说是完美的方式。只需将路线定义到每个动作中,例如
[Route("~/about-us")]
public IActionResult About()
{
return View();
}
这对我来说是完美的解决方案,因为它工作正常
- 1 回答
- 0 关注
- 158 浏览
添加回答
举报