locked
asp.net core webapi with single endpoint with multiple conditions RRS feed

  • Question

  • User1838940990 posted

    Hi All,

    hope you all are safe.

    We have asp.net core web api with multiple endpoints for different  categories 

    eg :    ww.url.com/category1/create

              ww.url.com/category2/create

    Since we don't to expose the category name , planning to expose single controller and category will be passed a field in parameter and palln to pu if condition to service the request 

    ww.url.com/create 

    [HttpPost("create")]
    
    public IActionResult Create( category category )
    
    {
    
         if category.Type ==category1
    
    {
    
    category1.service.create();
    
    }
    
    elseif category.Type ==category2
    
    {
    
    category2.service.create();
    
    }
    
    }

    We are going to have more than 8-10 conditon now and it can grow 

    or is there any pattern to handle these type of requirement like this ?

    have a nice day ahead

    thanks,

    Thursday, January 28, 2021 12:00 AM

All replies

  • User-1545767719 posted

    We are going to have more than 8-10 conditon now and it can grow 

    or is there any pattern to handle these type of requirement like this ?

    Rather than putting a lot of “if - else if- else” codes to select the category in the action method why don't you develop the Service class so that the Create method in it receives the argument "category" and return the object according to the argument given in the controller?

    Thursday, January 28, 2021 12:52 AM
  • User-474980206 posted

    the strategy pattern is a common refactor. google for examples. here are some simple implementations:

      https://blog.jamesmichaelhickey.com/strategy-pattern-implementations/

    Thursday, January 28, 2021 4:23 PM
  • User1838940990 posted

    Thanks Bruce, I am not much familiar with this pattern.

    Seems like this is something I am looking for, let me have look at this and update you if  I can implement this in my api

    Thursday, January 28, 2021 11:42 PM