0

I have a base AsyncController

BaseController : AsyncController
{ 
    [Authorize("Admin")]
    public virtual async Task<ActionResult> SomeMethod()
    {
        //code
    }
}

How it is correct to inheritance and override SomeMethod?

UserController : BaseController
{ 
    [Authorize("User")]
    public override Task<ActionResult> SomeMethod()
    {
        return base.SomeMethod()
    }
}

OR

UserController : BaseController
{ 
    [Authorize("User")]
    public override async Task<ActionResult> SomeMethod()
    {
        return await base.SomeMethod()
    }
}

P.S. Sorry for my english

Erik Philips
  • 53,428
  • 11
  • 128
  • 150
Roman Kiyashev
  • 150
  • 1
  • 11
  • Your two controllers are not related. Is `UserController` suppose to inherit from `BaseController`? – Nkosi Aug 06 '16 at 22:15
  • yes, `UserController` is inherited from `BaseController` – Roman Kiyashev Aug 06 '16 at 22:24
  • What version of MVC are you using. `AsyncController` was provided for backward compatibility with ASP.NET MVC 3. Otherwise you can simply use `Controller` ie: `public class BaseController : Controller`. – Nkosi Aug 06 '16 at 22:27
  • I use ASP.NET MVC 5 – Roman Kiyashev Aug 06 '16 at 22:30
  • Ok then use `Controler` not `AsyncController` as for inheritance of your controller, it doesn't matter you can use either one and it should work. It is more of an implementation detail. – Nkosi Aug 06 '16 at 22:34
  • 2
    @Nkosi is right. If you aren't doing anything in your overridden method that requires further awaiting, then your second option is best (just bubble up the task as is). If you are doing further operations that require awaiting, then your first option is best. – Jeremy Armstrong Aug 07 '16 at 15:07
  • 1
    Microsoft recommends suffixing base (not prefixing) for naming conventions `ControllerBase`. – Erik Philips Aug 07 '16 at 15:41
  • Just one tip: if the compiler isn't complaining (no errors and no warnings), then it's correct. – Paulo Morgado Aug 07 '16 at 17:34

1 Answers1

0

SomeMethod() is defined within your BaseController class. Therefore child classes should inherit from BaseController rather than AsyncController. To override the method, just add virtual keyword into the definition.

BaseController : AsyncController
{ 
    [Authorize("Admin")]
    public virtual async Task<ActionResult> SomeMethod()
    {
        //code
    }
}

Inheritance and override

UserController : BaseController
{ 
    [Authorize("User")]
    public override Task<ActionResult> SomeMethod()
    {
        return base.SomeMethod()
    }
}

Also I have noticed something odd in your Authorize attributes. If the base method is allow to Admin only and the child method is allow to User only, then you most likely end up being unable to execute the base method from the child class.

dotnetspark
  • 551
  • 4
  • 23