ASP.NET MVC ~ 404 「ファイルが見つかりません」の対処方法

ASP.NET MVC フレームワークは、ASP.NET ルーティングに依存してます。

これを利用するために、IIS の動作モードによっては ASP.NET ルーティングが認識されず、404エラーとなる場合があります。 IIS 7.0 統合モード以外では、MVC を実行するために対処が必要です。

方法 1. 拡張子によって対処する方法

サーバーに管理権限がある場合です。

C:\Program Files\Microsoft ASP.NET\ASP.NET MVC 1.0\Scripts 以下の、 registermvc.wsf を実行すると、.mvc という拡張子が登録されます。

次に、global.asax を次のように変更します。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace MvcApplication1
{
  
     public class MvcApplication : System.Web.HttpApplication
     {
         public static void RegisterRoutes(RouteCollection routes)
         {
             routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

             routes.MapRoute(
                 "Default",
                 "{controller}.mvc/{action}/{id}",
                 new { action = "Index", id = "" }
               );

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


         }

         protected void Application_Start()
         {
             RegisterRoutes(RouteTable.Routes);
         }
     }
}

方法 2. ホスティング等、管理権限が無い場合

ホスティング環境のように、スクリプトを実行できない場合は、 次のような方法で対処します。要は .aspx に処理させます。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace MvcApplication1
{
  
     public class MvcApplication : System.Web.HttpApplication
     {
         public static void RegisterRoutes(RouteCollection routes)
         {
             routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

             routes.MapRoute(
                 "Default",
                 "{controller}.aspx/{action}/{id}",
                 new { action = "Index", id = "" }
               );

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


         }

         protected void Application_Start()
         {
             RegisterRoutes(RouteTable.Routes);
         }
     }
}

global.asax の書き換え後、Visual Studio にてプロジェクトのリビルドを行うことで利用可能になるはずです。

».NET Framework による開発目次へ戻る

ここまでお読みいただき、誠にありがとうございます。SNS 等でこの記事をシェアしていただけますと、大変励みになります。どうぞよろしくお願いします。

© 2024 Web/DB プログラミング徹底解説