Friday, July 20, 2018

Registering Actions for ControllerModel in ASP.NET Core

Leave a Comment

I am trying to add a new ActionModel for a ControllerModel in an implementation of IControllerModelConvention, but I cannot find any documentation or examples of how this model system works or how to do this correctly. I am able to add a new ActionModel easily enough, but it is not routable once the application is running:

var action = new ActionModel(method, new object[] { new HttpGetAttribute("/test") }) {     Controller = controller,     ActionName = "test" }; controller.Actions.Add(action); 

It seems I need to add a selector to the action, perhaps other properties as well, but I haven't been able to find one that exposes this action. Also unsure if my attributes are correct/redundant. Ultimately I would like to add multiple actions that do not map 1:1 to the methods in the controller.

1 Answers

Answers 1

I've made it work similiar to your approach. Maybe this can help you:

Controller

public class TestController : Controller {     public IActionResult Index()     {         return Ok(new string[] { "Hello", "World" });     } } 

Model Convention

public class TestControllerModelConvention : IControllerModelConvention {     public void Apply(ControllerModel controller)     {         Type controllerType = typeof(TestController);         MethodInfo indexAction = controllerType.GetMethod("Index");          var testAction = new ActionModel(indexAction, new[] { new HttpGetAttribute("/test") })         {             ActionName = "Index",             Controller = controller         };         controller.Actions.Add(testAction);     } } 

Startup

public void ConfigureServices(IServiceCollection services) {     // other initialitation stuff      services.AddMvc(options =>     {         options.Conventions.Add(new TestControllerModelConvention());     }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1); } 

Now when I start the application and browse "/test" it will hit the controller action.

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment