3

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.

Roman Koliada
  • 4,286
  • 2
  • 30
  • 59
Kamran Shahid
  • 3,954
  • 5
  • 48
  • 93
  • You have two extension method with return type IActionResult. – Llazar Oct 03 '18 at 10:41
  • they are just a sample. i have first tried with controller class, then ControllerBase class but neither compiled – Kamran Shahid Oct 03 '18 at 10:44
  • Maybe you need to implement first the IActionResult but why you want to modify it? – Llazar Oct 03 '18 at 10:49
  • How exactly are you calling these extension methods from your controller? This.Change? Have you added namespace? Personally, id prefer to create my own controller class and place common controller methods id need and flexibility to override behavior if required. Example: MyControllerBase : Controller – Migg Oct 03 '18 at 10:57
  • 1
    "but neither worked" please specify exactly what you problem is: a compilation error, a runtime error, it doesn't behave as you expected etc. – Martin Ullrich Oct 03 '18 at 11:44
  • From my business logic layer i am returning some Object. On that Object's response code i wanted to return different actionResult like Ok(),notfound(),forbidden e.t.c. But i don't wanted to repeat the logic in each controller method – Kamran Shahid Oct 03 '18 at 14:11

1 Answers1

1

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.

Rzassar
  • 2,117
  • 1
  • 33
  • 55