如何从我自己的 bascontroller 覆盖泛型方法 class

How to override generic method from my own bascontroller class

我有一个基本控制器class,MyBaseController。我如何覆盖另一个继承自 MyBaseController 的控制器 class 中的方法?每个控制器的视图模型都不同。

public class MyBaseController<T> : ControllerBase where T : class
{
    public VsBaseController()
    {
    }

    [HttpGet]
    public virtual async Task<IActionResult> GetAsync([FromQuery] string QueryParams)
    {
        return null;
    }

    [HttpDelete("{id}")]
    public virtual async Task<IActionResult> DeleteAsync(int id)
    {
        return null;
    }

    [HttpPost]
    [ServiceFilter(typeof(ValidationFilter))]
    protected virtual async Task<IActionResult> CreateAsync(T ViewModel)
    {
        return null;
    }

    [HttpPut]
    public virtual async Task<IActionResult> UpdateAsync(T ViewModel, int Id)
    {
        return null;
    }
}

在后代控制器中,我有以下代码:

[HttpPost]
public override async Task<IActionResult> CreateAsync(MyViewModel ViewModel)
{
    var Response = await _MyService.New(ViewModel);
    return Response;
}

并且在构建应用程序时出现以下错误:

CS0115: no suitable method found to override

您需要在派生控制器中设置通用类型,如下例所示:

public class MyBaseController<T> : ControllerBase where T : class
    {
        public MyBaseController()
        {
        }

        [HttpGet]
        public virtual async Task<IActionResult> GetAsync([FromQuery] string QueryParams)
        {
            return null;
        }

        [HttpDelete("{id}")]
        public virtual async Task<IActionResult> DeleteAsync(int id)
        {
            return null;
        }

        [HttpPost]
        // [ServiceFilter(typeof(ValidationFilter))]
        protected virtual async Task<IActionResult> CreateAsync(T ViewModel)
        {
            return null;
        }

        [HttpPut]
        public virtual async Task<IActionResult> UpdateAsync(T ViewModel, int Id)
        {
            return null;
        }
    }

因此,如果您有一个名为 MyModel 的 ViewModel,则可以这样使用它:

    public class MyModel
    {

    }

    public class TestDerivedController : MyBaseController<MyModel>
    {
        public override Task<IActionResult> UpdateAsync(MyModel ViewModel, int Id)
        {
            return base.UpdateAsync(ViewModel, Id);
        }
    }