c# - 如何使用 ASP.NET MVC 中的路由修复 404?

标签 c# asp.net-mvc asp.net-mvc-3 routing

我在尝试让路由与 ASP.NET MVC 3.0 一起工作时遇到问题。我声明了以下路线:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
        "Default",
        "{controller}/{action}/{id}",
    new { controller = "Home", action = "RsvpForm", id = UrlParameter.Optional } 
    );

    routes.MapRoute(
        "TestRoute",
        "{id}",
        new { controller = "Product", action = "Index3", id = UrlParameter.Optional }
    );

    routes.MapRoute(
        "TestRoute2",
        "{action}",
        new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
}

当我访问时:

http://localhost

该站点正常运行,并且似乎命中了 Default 路由。

当我访问时:

http://localhost/1

我得到一个 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: /1

以下是这些路由对应的操作:

public ActionResult Index3(int? id)
{
    Product myProduct = new Product
    {
        ProductID = 1,
        Name = "Product 1 - Index 3",
        Description = "A boat for one person",
        Category = "Watersports",
        Price = 275M
    };

    Product myProduct2 = new Product
    {
        ProductID = 2,
        Name = "Product 2 - Index 3",
        Description = "A boat for one person",
        Category = "Watersports",
        Price = 275M
    };

    ViewBag.ProcessingTime = DateTime.Now.ToShortTimeString();

    if (id == 1)
        return View("index", myProduct);
    else
        return View("index", myProduct2);
}

如何构建我的路线,以便正确命中所有三种操作方法?

最佳答案

ASP.NET MVC 路由从上到下评估路由。因此,如果两条路线匹配,它命中的第一个路线(靠近 RegisterRoutes 方法的“顶部”的路线)将优先于后续路线。

考虑到这一点,您需要做两件事来解决您的问题:

  1. 您的默认路线应该在底部。
  2. 如果它们包含相同数量的段,则您的路线需要对其进行约束:

有什么区别:

example.com/1

example.com/index

对于解析器,它们包含相同数量的段,并且没有区分符,因此它将命中列表中匹配的第一个路由。

要解决这个问题,您应该确保使用 ProductIds 的路由采用约束:

routes.MapRoute(
    "TestRoute",
    "{id}",
    new { controller = "Product", action = "Index3", id = UrlParameter.Optional },
    new { id = @"\d+" } //one or more digits only, no alphabetical characters
);

您的设置还有其他问题,但我马上想到了这两件事。

关于c# - 如何使用 ASP.NET MVC 中的路由修复 404?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8737535/

相关文章:

c# - WCF 是否在多个线程上运行 session ?

c# - HTTP 错误 404.13 - asp.net core 2.0

javascript - 仅当列表中添加了 ajax 请求时才调用 ajax 请求

jquery - 更改日期格式验证、mvc 3 和 jQuery

c# - ASP.NET MVC 3 : Blog Posts's model Tags Binding Best Practices

javascript - 如何创建一个包含另一个 Angular Cli 的 Angular Cli 应用程序?

c# - OutOfMemoryException - 如何发现内存泄漏?

c# - 在 C# 中访问 HTML 页面

c# - Java中数组继承自什么?我可以这样做吗?

asp.net-mvc - 使用 MEF 构建具有 n 层松散耦合的 MVC ASP.NET 应用程序