mardi 27 novembre 2018

C# asp.net web api best way or design pattern to implement DRY principle

I have the following two action methods in my controller. Both take the same parameter and do the same validation of the model. it differs at only one line where it makes a call to a service method.

Is there a better way to refactor this code?

[HttpPost]
public async Task<IActionResult> Search([FromBody]AggregateSearchCriteria criteria)
{
    if (criteria == null || !criteria.Aggregates.Any())
    {
        return BadRequest();
    }

    var providers = Request.Headers["providers"];

    if (providers.Equals(StringValues.Empty))
        return BadRequest();

    criteria.Providers = providers.ToString().Split(',').ToList();

    ModelState.Clear();

    TryValidateModel(criteria);

    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    var result = await _searchService.Search(criteria);

    return Ok(result);
}

[HttpPost("rulebreak")]
public async Task<IActionResult> SearchRuleBreak([FromBody]AggregateSearchCriteria criteria)
{
    if (criteria == null || !criteria.Aggregates.Any())
    {
        return BadRequest();
    }

    var providers = Request.Headers["providers"];

    if (providers.Equals(StringValues.Empty))
        return BadRequest();

    criteria.Providers = providers.ToString().Split(',').ToList();

    ModelState.Clear();

    TryValidateModel(criteria);

    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    var result = await _searchService.SearchRuleBreak(criteria);

    return Ok(result);
}

Aucun commentaire:

Enregistrer un commentaire