ASP.NET MVC路由 - 试图在URL中有一个名字 [英] ASP.NET MVC routing - trying to have a name in the url

查看:101
本文介绍了ASP.NET MVC路由 - 试图在URL中有一个名字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有以下途径:

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.IgnoreRoute("{resource}.gif/{*pathInfo}");

        MvcRoute.MappUrl("{controller}/{action}/{ID}")
            .WithDefaults(new { controller = "home", action = "index", ID = 0 })
            .WithConstraints(new { controller = "..." })
            .AddWithName("default", routes)
            .RouteHandler = new MvcRouteHandler();

        MvcRoute.MappUrl("{title}/{ID}")
            .WithDefaults(new { controller = "special", action = "Index" })
            .AddWithName("view", routes)
            .RouteHandler = new MvcRouteHandler();

该SpecialController有一个方法:公共的ActionResult指数(INT ID)

The SpecialController has a method : public ActionResult Index(int ID)

每当我指出我的浏览器:的http://主机名/测试/ 5 我收到以下错误:

whenever i point my browser to : http://hostname/test/5 i get the following error:

参数字典包含SpecialController'不可为空的类型'System.Int32'的方法'System.Web.Mvc.ActionResult指数(Int32)已'参数'ID'空项。为了使参数可选其类型应该是引用类型或可空类型。
参数名:参数
说明:执行当前Web请求的执行过程中发生未处理的异常。请检查堆栈跟踪有关该错误的详细信息以及它起源于code。

The parameters dictionary contains a null entry for parameter 'ID' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Index(Int32)' in 'SpecialController'. To make a parameter optional its type should be either a reference type or a Nullable type. Parameter name: parameters Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

你有任何想法,为什么会这样?我用mvccontrib路线调试器和似乎路由访问的预期

Do you have any idea why is that? I used the mvccontrib route debugger and it seems that the route is accessible as expected

推荐答案

这正是作为错误消息说。你已经有了一个被称为ID,它没有缺省值的参数,但你的方法需要一个非空的int类型。因为没有默认值,它试图在零中度过的,但...它不能,因为你的int参数就是非空的。

It's exactly as the error message says. You've got a parameter called "ID" which has no default value, but your method is expecting a non-nullable int. Because there is no default value, it's trying to pass in a "null", but... it can't, because your int parameter is non-nullable.

路由调试可能不检查类型为空。

The route debugger probably doesn't check types for nullable.

要解决这个问题:

 MvcRoute.MappUrl("{title}/{ID}")
        .WithDefaults(new { controller = "special", action = "Index", ID = 0 })
        .AddWithName("view", routes)
        .RouteHandler = new MvcRouteHandler();

这篇关于ASP.NET MVC路由 - 试图在URL中有一个名字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆