c# - RouteConfig 设置接受可选参数

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

我在设置 RouteConfig 文件以接受可选记录 ID 作为 URL 的一部分时遇到问题,如下例所示。

http://localhost/123 (used while debugging locally)

or even

http://www.foobar.com/123 

理想情况下,我希望将记录 ID(在上面的示例中为 123)作为参数传递给 Home Controller 的 Index View 。我曾认为默认的 routeconfig 就足够了(使用 ID 作为可选元素),但显然该应用程序显然试图将浏览器定向到一个名为“123”的 View ,这显然不存在。

我当前的 RouteConfig.cs 如下所示:

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

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

如有任何帮助,我们将不胜感激。

最佳答案

你的路线说:

{controller}/{action}/{id}

这是您的网站,然后是您的 Controller ,然后是您的操作,最后是一个 ID。

您只需要站点然后是 id:

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

这会在

处触发 Controller
public class DefaultController : Controller
{
    public ActionResult Index(int id)
    {
    }
}

关于c# - RouteConfig 设置接受可选参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24330596/

相关文章:

c# - 从 XSL :FO using C# 生成 HTML

c# - 在 View 中使用接口(interface)类型作为模型并使用真实类型属性和验证的最佳实践

c# - 如何在 POSTAL MVC 中而不是在 WEB.Config 中设置 SMTP 客户端

C# MVC 在默认路由上使用参数

不等于约束的ASP.NET路由

c# - 如何找到在执行期间调用特定方法的单元测试?

c# - 在运行时将图像拖到 RichTextBox 内的 FlowDocument 中

c# - 异步 TCP 操作期间的 AccessViolation

asp.net-mvc - 默认模型绑定(bind)器不起作用

asp.net-mvc - 如何在 ASP.NET MVC 4 中定义一个捕获(绝对)所有路由