为了好玩,我想我会试试这个:
public class RouteConfig
{
public static void BuildProxy()
{
AssemblyName dynasm = new AssemblyName("Dynasm");
AssemblyBuilder asmBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(dynasm, AssemblyBuilderAccess.Run);
ModuleBuilder modBuilder = asmBuilder.DefineDynamicModule(dynasm.Name);
TypeBuilder typeBuilder = modBuilder.DefineType("MyProxyController");
MethodBuilder action = typeBuilder.DefineMethod("Action", MethodAttributes.Public, CallingConventions.Standard,
typeof(String), Type.EmptyTypes);
ILGenerator ilGen = action.GetILGenerator();
ilGen.Emit(OpCodes.Ldstr, "The value to return");
ilGen.Emit(OpCodes.Ret);
Activator.CreateInstance(typeBuilder.CreateType());
}
public static void RegisterRoutes(RouteCollection routes)
{
BuildProxy();
routes.AppendTrailingSlash = true;
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute("Proxy", "Proxy/Action", new { controller = "MyProxy", action = "Action" });
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
这个想法基本上是在运行时生成一个类,并将其用作控制器。但是由于某种原因,当我导航到/Proxy/Action
路由引擎时似乎看不到我的课程。这是为什么?