Search code examples
c#.net-coreextension-methodsasp.net-core-webapiasp.net-core-2.1

How to add extension method in .Net core API controller


I have to a modify the IActionResult according to certain property of my custom object.

I am trying different ways to change but neither worked

public static class ExtensionMethods
{

    public static IActionResult Change(this Controller controller, ExternalResponse obj)
    {
        if (case 1)
        {
            return Ok(extResp);
        }
        else if(case 2)
        {
            return NotFound(extResp);
        }
        else if(case 31)
        {
            return Unauthorized();
        }
        else
        {
            return BadRequest(extResp);
        }   
    }

    public static IActionResult ChangeTwo(this ControllerBase controller, ExternalResponse obj)
    {
        if (case 1)
        {
            return Ok(extResp);
        }
        else if(case 2)
        {
            return NotFound(extResp);
        }
        else if(case 31)
        {
            return Unauthorized();
        }
        else
        {
            return BadRequest(extResp);
        }   
    }
}

Please suggest what can I do.


Solution

  • Actually the problem is that you cannot add extension method to an abstract class, and ControllerBase is an abstract class here. Here is why you cannot have such extension method.