所以我想让我的网址看起来与此类似:
example.com
、example.com/contact
、example.com/sign-up
、example.com/account
而不是默认的 MVC 方式,如下所示:
example.com
、example.com/Home/Contact
、example.com/Account/SignUp
、example.com/帐户/帐户
所有 HomeController
View 都可以正常工作,但我的 AccountController
却不能。
当访问 example.com/account
时,我收到一条错误消息:
The resource cannot be found.
这是我的RouteConfig
:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.LowercaseUrls = true;
routes.MapRoute(
name: "Default",
url: "{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Account",
url: "{action}/{id}",
defaults: new { controller = "Account", action = "Account", id = UrlParameter.Optional }
);
}
因为我想将 Account/SignUp
View 显示为 /sign-up
,所以我在 AccountController
中添加了一些自定义代码。
// GET: Account
public ActionResult Account()
{
return View();
}
// GET: Sign Up
[ActionName("Sign-Up")]
public ActionResult SignUp()
{
return View("SignUp");
}
两种格式 /account
或 /account/account
都会给我带来与之前相同的错误。
但是 /about
、/contact
等则不然。
感谢任何帮助,谢谢!
P.S 这是我的文件夹结构:
> Views
-> Account
--> Account.cshtml
--> SignUp.cshtml
-> Home
--> About.cshtml
--> Contact.cshtml
--> Index.cshtml
最佳答案
路线设置需要更加明确。
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.LowercaseUrls = true;
routes.MapRoute(
name: "Account",
url: "account/{action}/{id}",
defaults: new { controller = "Account", action = "Account", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
关于c# - 自定义路由 ASP.NET MVC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59467536/