Server.TransferRequest
MVCでは完全に不要です。これは、要求がページに直接送信され、要求を別のページに転送する方法が必要だったため、ASP.NETでのみ必要だった時代遅れの機能です。最新バージョンのASP.NET(MVCを含む)には、目的のリソースに直接ルーティングするようにカスタマイズできるルーティングインフラストラクチャがあります。要求をコントローラーに直接送信して必要なアクションを実行できる場合は、要求をコントローラーに到達させて別のコントローラーに転送するだけでは意味がありません。
さらに、元のリクエストに応答しているTempData
ため、リクエストを適切な場所にルーティングするためだけに、ストレージやその他のストレージに何かを入れる必要はありません。代わりに、元の要求をそのままにしてコントローラーアクションに到達します。また、このアプローチは完全にサーバー側で行われるため、Googleがこのアプローチを承認するので安心できます。
IRouteConstraint
との両方からかなりのことができますがIRouteHandler
、ルーティングの最も強力な拡張ポイントはRouteBase
サブクラスです。このクラスは、着信ルートと発信URL生成の両方を提供するように拡張できます。これにより、URLとURLが実行するアクションに関係するすべてのことをワンストップショップで行うことができます。
したがって、2番目の例に従って、からに/
移動する/home/7
には、適切なルート値を追加するルートが必要です。
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// Routes directy to `/home/7`
routes.MapRoute(
name: "Home7",
url: "",
defaults: new { controller = "Home", action = "Index", version = 7 }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
ただし、ランダムなページがある元の例に戻ると、実行時にルートパラメータを変更できないため、より複雑になります。RouteBase
したがって、次のようにサブクラスを使用して実行できます。
public class RandomHomePageRoute : RouteBase
{
private Random random = new Random();
public override RouteData GetRouteData(HttpContextBase httpContext)
{
RouteData result = null;
// Only handle the home page route
if (httpContext.Request.Path == "/")
{
result = new RouteData(this, new MvcRouteHandler());
result.Values["controller"] = "Home";
result.Values["action"] = "Index";
result.Values["version"] = random.Next(10) + 1; // Picks a random number from 1 to 10
}
// If this isn't the home page route, this should return null
// which instructs routing to try the next route in the route table.
return result;
}
public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
{
var controller = Convert.ToString(values["controller"]);
var action = Convert.ToString(values["action"]);
if (controller.Equals("Home", StringComparison.OrdinalIgnoreCase) &&
action.Equals("Index", StringComparison.OrdinalIgnoreCase))
{
// Route to the Home page URL
return new VirtualPathData(this, "");
}
return null;
}
}
次のようなルーティングに登録できます。
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// Routes to /home/{version} where version is randomly from 1-10
routes.Add(new RandomHomePageRoute());
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
上記の例では、ユーザーがアクセスしたホームページのバージョンを記録したCookieも保存して、ユーザーが戻ったときに同じホームページのバージョンを受け取るようにすることも意味があることに注意してください。
このアプローチを使用すると、ルーティングをカスタマイズしてクエリ文字列パラメーターを考慮に入れ(デフォルトでは完全に無視されます)、それに応じて適切なコントローラーアクションにルーティングできることにも注意してください。
その他の例