sircodesalot
sircodesalot

Reputation: 11439

Can a dynamic proxy be used as a controller?

For fun, I thought I'd try this out:

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 }
        );
    }
}

The idea is basically to generate a class at runtime, and use it as a controller. For some reason though, When I navigate to /Proxy/Action the routing engine doesn't seem to see my class. Why is that?

Upvotes: 1

Views: 300

Answers (1)

Fals
Fals

Reputation: 6839

The MVC route engine looks for Controller classes to route the request to the correct place.

You should implement an IRouteHandler interface for this one instead! Here's a dummy example just for you start Routing for Proxy

Upvotes: 2

Related Questions