在ASP.NET Core中为ControllerModel注册动作

时间:2018-07-11 18:24:55

标签: asp.net asp.net-core routing asp.net-core-mvc

我正在尝试在ActionModel的实现中为ControllerModel添加新的IControllerModelConvention,但是找不到任何有关此模型系统如何工作或如何做的文档或示例。这是正确的。我能够很容易地添加一个新的ActionModel,但是一旦应用程序运行,它就无法路由:

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

似乎我需要为该动作添加一个选择器,也许还需要添加其他属性,但是我一直无法找到一个公开此动作的选择器。也不确定我的属性是否正确/冗余。最终,我想添加多个未将1:1映射到控制器中方法的动作。

1 个答案:

答案 0 :(得分:1)

我已使其工作方式类似于您的方法。也许这可以帮助您:

控制器

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

示范公约

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

启动

public void ConfigureServices(IServiceCollection services)
{
    // other initialitation stuff

    services.AddMvc(options =>
    {
        options.Conventions.Add(new TestControllerModelConvention());
    }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}

现在,当我启动应用程序并浏览“ / test”时,它将执行控制器操作。