2009-07-25 25 views
2

に名前を持ってしようとしている: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は方法があります:私はhttp://hostname/test/5に私のブラウザをポイントするたびに、public ActionResult Index(int ID)

を私は次のエラーを取得する:

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ルートデバッガを使用して、ルートが期待通りにアクセス可能であるようです。

答えて

2

エラーメッセージと同じです。 "ID"というパラメータにはデフォルト値はありませんが、あなたのメソッドはnullを許さないintを期待しています。デフォルト値がないので、それは "null"を渡そうとしていますが、あなたのintパラメータがnull値ではないのでできません。

ルートデバッガは、nullableの型をチェックしていない可能性があります。

それを修正するには、次の

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

同様に、同じ例外がスローされます)。 – Yannis

+0

MappUrl拡張メソッドのコードを投稿できますか? – womp

+0

それは私のコードではありません。それはmvccontribの一部です。私はソースを利用できません。 – Yannis

4

私はあなたがデフォルトの前に、あなたのカスタムルートを置くべきだと思います。

http://weblogs.asp.net/scottgu/archive/2007/12/03/asp-net-mvc-framework-part-2-url-routing.aspx

+0

+1あなたがここにいるかもしれないと思います。 Phil Haackの記事「re route debugging」もチェックしてください:http://haacked.com/archive/2008/03/13/url-routing-debugger.aspx –

+0

それは解決策でもありません。しかし、あなたは最後の手段として扱われるために、デフォルトで最後に行かなければならないという点で正しいです。 – Yannis

+0

これはmvccontribの不具合かもしれません。私はRouteCollection(mvccontribを使用していない)に直接ルートをマッピングすることでシナリオを試しましたが、期待通りに機能しました。 –

3

は、私は解決策は、あなたの行動のパラメータ名と一致しませんでしたあなたのルート変数名だった提案します。

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

これは動作します:

// Controller.cs 
public ActionResult Index(int ID){...} 

をどこでこれはないだろう:私は前にしようとした私は、デフォルトのIDを追加した後でも、ケースの原因(厥と思ういけない

// Controller.cs 
public ActionResult Index(int otherID) {...} 
+0

私は上記のルーティングコードパターンに慣れていません。 .WithConstraints(new {controller = "..."})の意味は何ですか。 と.AddWithName( "default"、routes) ここでコントローラ名は何ですか? – Thomas

関連する問題