Home > Net >  How to override generic method from my own bascontroller class
How to override generic method from my own bascontroller class

Time:05-28

I have a base controller class, MyBaseController. How can I override the methods in another controller class which inherits from MyBaseController? The view model is different in every controller.

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

In the descendent controller, I have the following code:

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

And when building the app I get the following error:

CS0115: no suitable method found to override

CodePudding user response:

You need to set the generic type in your derived Controller like the following example:

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

So if you have a ViewModel called MyModel then use it like this:

    public class MyModel
    {

    }

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