如何在 MVC 中为类别使用短网址

How to use short urls for categories in MVC

包含产品类别的短网址,如

http://example.com/Computers

应该在 ASP.NET MVC 4 购物车中使用。 如果没有控制器,则应调用带有 id 参数作为 Computers 的 Home Index 方法。

我尝试使用

将 id 参数添加到家庭控制器
public class HomeController : MyControllerBase
{
    public ActionResult Index(string id)
    {
        if (!string.IsNullOrWhiteSpace(id))
        {
            return RedirectToAction("Browse", "Store", new
            {
                id = id,
            });

        }
            return View("Index", new HomeIndexViewModel());
    }

http://example.com/Computers 导致 404 错误

Server Error in '/' Application.

The resource cannot be found.

Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.

Requested URL: /Computers

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.6.1073.0

如果 http://example.com/....

中斜杠后没有定义控制器,如何强制调用某些控制器

使用 MVC 默认路由:

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.IgnoreRoute("{*favicon}", new { favicon = @"(.*/)?favicon.ico(/.*)?" });
        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}

看起来 MVC 忽略了路由参数:

defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }

如何解决这个问题?

你的问题是因为 aspnet mvc 试图找到一个名称为 Computers 的控制器,而你的控制器是 Home,你可以在名称为 Default 的路由之前添加这样的新路由:

routes.MapRoute(
            name: "Computers",
            url: "Computers",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );

在上述情况下,您正在创建一个与 url http://domain.com/Computers 匹配的路由,并且该路由将由 HomeController 管理。

此外,根据您的评论,您可以使用如下路线:

routes.MapRoute(
                name: "Default",
                url: "{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );