gpt4 book ai didi

c# - ASP.NET Web API Controller 最佳实践 - Action 定义

转载 作者:行者123 更新时间:2023-11-30 20:02:24 25 4
gpt4 key购买 nike

我遇到的情况是,我的 Web API Controller 中的 HttpGet 操作有多种方法可以根据查询字符串中指定的参数进行调用。

我需要能够处理以下 GET 请求:

 ~/businesses/{businessId}
~/businesses?hasOwnProperty={propertyName}
~/businesses?latitude={lat}&longitude={long}&hasOwnProperty={propertyName}

代码示例 1:

[HttpGet]
public HttpResponseMessage Get(string hasOwnProperty, ODataQueryOptions<Core.Models.Entities.Business> query)
{
var businessesREST = _businessRepo.Gets(hasOwnProperty, query);

response = Request.CreateResponse(HttpStatusCode.OK, businessesREST);
response.Headers.Location = new Uri(businessesREST.Href);

return response;
}

[HttpGet]
public HttpResponseMessage Get(double latitude, double longitude, string hasOwnProperty, ODataQueryOptions<Core.Models.Entities.Business> query)
{
var businessesREST = _businessRepo.GetsByLatLong(latitude, longitude, hasOwnProperty, query);

response = Request.CreateResponse(HttpStatusCode.OK, businessesREST);
response.Headers.Location = new Uri(businessesREST.Href);

return response;
}

[HttpGet]
public HttpResponseMessage GetBusiness(string businessId, ODataQueryOptions<Core.Models.Entities.Business> query)
{
var businessREST = _businessRepo.Get(businessId, query);

response = Request.CreateResponse(HttpStatusCode.OK, businessREST);
response.Headers.Location = new Uri(businessREST.Href);

return response;
}

有人建议我结合以下方法。

代码示例 2:

[HttpGet]
public HttpResponseMessage Get(string businessId, double latitude, double longitude, string hasOwnProperty, ODataQueryOptions<Core.Models.Entities.Business> query)
{

if (!String.IsNullOrEmpty(businessId))
{
//GET ~/businesses/{businessId}
var businessREST = _businessRepo.Get(businessId, query);

response = Request.CreateResponse(HttpStatusCode.OK, businessREST);
response.Headers.Location = new Uri(businessREST.Href);
}
else
{
//GET ~/businesses?hasOwnProperty={propertyName}
//GET ~/businesses?latitude={lat}&longitude={long}&hasOwnProperty={propertyName}
var businessesREST = (latitude == double.MinValue || longitude == double.MinValue)
? _businessRepo.Gets(hasOwnProperty, query)
: _businessRepo.GetsByLatLong(latitude, longitude, hasOwnProperty, query);

response = Request.CreateResponse(HttpStatusCode.OK, businessesREST);
response.Headers.Location = new Uri(businessesREST.Href);
}

return response;

}

我很好奇当前广泛接受的关于 Action 定义的最佳实践及其背后的原因。

最佳答案

由于以下几个原因,使用单独的方法要好得多:

  1. 单独对各个操作进行单元测试要容易得多。
  2. 具有单独的操作可以大大降低更改一个操作的实现而意外更改其他操作的实现的可能性。
  3. 组合这些方法意味着一堆参数将为 null,并且您将有一个关于哪些参数应该一起设置以及哪些参数在不同情况下应该为 null 的隐含契约。这就是您必须添加评论的原因。单独的操作是 self 记录的,因为它们使契约(Contract)更清楚地说明如何调用您的 API。

关于c# - ASP.NET Web API Controller 最佳实践 - Action 定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16847643/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com