实现Web API DRY原理的设计模式

时间:2018-11-27 10:47:04

标签: c# design-patterns asp.net-core asp.net-core-webapi dry

我的控制器中有以下两种操作方法。两者都采用相同的参数并对模型进行相同的验证。它仅在调用服务方法的一行上有所不同。

是否有更好的方法来重构此代码?

[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);
}

3 个答案:

答案 0 :(得分:1)

类似的事情可能是一个开始。

[HttpPost]
public async Task<IActionResult> Search([FromBody]AggregateSearchCriteria criteria)
{
    return await Common(criteria, c => _searchService.Search(c));
}

public async Task<IActionResult> SearchRuleBreak([FromBody]AggregateSearchCriteria criteria)
{
    return await Common(criteria, c => _searchService.SearchRuleBreak(c));
}

private async Task<IActionResult> Common(AggregateSearchCriteria criteria, Func<List<string>, Task<???>> action)
{
    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 action.Invoke(criteria);

    return Ok(result);
}

答案 1 :(得分:1)

在这种情况下,模板模式是一种解决方法。虽然与验证无关。而且您还必须注意控制器的依赖性。请注意,以下代码如果不进行一些更改将无法自动运行。

public abstract class BaseSearch
{
    public Task<IActionResult> Apply(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 ServiceCall(criteria);

        return Ok(result);
    }

    protected abstract async IActionResult ServiceCall(AggregateSearchCriteria criteria);
}

public class Search : BaseSearch
{
    protected async Task<IActionResult> ServiceCall(AggregateSearchCriteria criteria)
    {
        return await _searchService.Search(criteria);
    }
}

public class SearchRuleBreak : BaseSearch
{
    protected async Task<IActionResult> ServiceCall(AggregateSearchCriteria criteria)
    {
        return await _searchService.SearchRuleBreak(criteria);
    }
}

然后在通话时

[HttpPost]
public async Task<IActionResult> Search([FromBody]AggregateSearchCriteria criteria)
{
    return await new Search().Apply(criteria);
}

[HttpPost("rulebreak")]
public async Task<IActionResult> SearchRuleBreak([FromBody]AggregateSearchCriteria criteria)
{
    return await new SearchRuleBreak().Apply(criteria);
}

注意:随着当今语言的功能越来越多,正如@stuartd所建议的那样,“将函数作为参数发送”也是一种有效的方法。

答案 2 :(得分:0)

您可以为模型AggregateSearchCriteria实现IValidatableObject,并将所有验证逻辑移入其中。对于提供者,您可以将其添加到模型中并编写自定义数据绑定器,该绑定器将绑定标头中的值,也可以编写一个逗号数组绑定器,以将值拆分为数组。

public class AggregateSearchCriteria : IValidatableObject
{
    [FromHeader]
    public IList<string> Providers { get; set; } = new List<string>();

    public IList<string> Aggregates { get; set; } = new List<string>();
    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        var result = new List<ValidationResult>();
        if (!Providers.Any())
        {
            result.Add(new ValidationResult("No Providers", new[] { nameof(AggregateSearchCriteria.Providers) }));
        }
        if (!Aggregates.Any())
        {
            result.Add(new ValidationResult("No Aggregates", new[] { nameof(AggregateSearchCriteria.Aggregates) }));
        }
        return result;
      }
   }

    [HttpPost]
    public async Task<IActionResult> Search([FromBody]AggregateSearchCriteria criteria)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        var result = await _searchService.Search(criteria);

        return Ok(result);
    }