user419022
user419022

Reputation: 121

Can I create a common request parameter for multiple API controllers?

I have multiple ASP.NET Core Web API controller classes with 95% similar code and only different GET parameters. Two of such classes are shown below:

Code for OrdersController.cs file:

class OrdersController : Controller
{
  public async Task<JsonResult> GetAsync([FromBody]ZoneRequest filterParameters)
  {
    // A lot of common code here
    var url = FetchOrdersValFromConfigFile();
    var response = await this.httpClient.PostAsync(proxyUrl, new StringContent(Convert.ToString(JsonConvert.SerializeObject(filterParameters)), Encoding.UTF8, "application/json"));
   // Again a lot of common code here
  }
}
public class ZoneRequest
{
    public string postCode { get; set; }
    public string suburb { get; set; }
}

Code for PricesController.cs file:

class PricesController : Controller
{
  public async Task<JsonResult> GetAsync([FromBody]ServiceRequest req)
  {
    // A lot of common code here
    var url = FetchPricesValFromConfigFile();
    var response = await this.httpClient.PostAsync(url, new StringContent(Convert.ToString(JsonConvert.SerializeObject(req)), Encoding.UTF8, "application/json"));
    // Again a lot of common code here
  }
}
public class ServiceRequest
{
    public string serviceName { get; set; }
    public string ClientCode { get; set; }
    public string ServiceCode { get; set; }
}

As you can see the only difference is in the GET parameter request type. I have a dozen of such classes. How can I remove the duplicate code from all those classes. I know that in non-API code, such cases can be solved by creating a parent parameter class with common fields and inheriting other DTO classes from it but I don't know what is the Web API equivalent of this solution.

Upvotes: 1

Views: 240

Answers (1)

Kazi Rahiv
Kazi Rahiv

Reputation: 681

Create a base controller and put your common codes/properties there as protected so you can reuse the logic in your inherited class.

public class BaseController : Controller {
    protected void ProcessCommonCodes()
    {
        //Process your common code operation here
    }
}

Then use the base controller in your other controller classes

class OrdersController : BaseController 
{
  public async Task<JsonResult> GetAsync([FromBody]ZoneRequest filterParameters)
  {
    ProcessCommonCodes();
    var url = FetchOrdersValFromConfigFile();
    var response = await this.httpClient.PostAsync(proxyUrl, new StringContent(Convert.ToString(JsonConvert.SerializeObject(filterParameters)), Encoding.UTF8, "application/json"));
    ProcessCommonCodes();
  }
}

Upvotes: 1

Related Questions