动态代理可以用作控制器吗?

时间:2013-06-28 14:30:56

标签: c# asp.net-mvc-4

为了好玩,我想我会试试这个:

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时,路由引擎似乎没有看到我的课程。那是为什么?

1 个答案:

答案 0 :(得分:2)

MVC route engine查找Controller个类以将请求路由到正确的位置。

您应该为此实现IRouteHandler接口!这是一个虚拟的例子,只为你开始Routing for Proxy