0

我是 ASP.NET Web API 的新手,我有一个问题。我通过以下方式调用 API:

 Uri uri = new Uri(ConfigurationManager.AppSettings["ServiceUrl"] + "/api/document/GetByDate?date=" + date;
 HttpClient client = new HttpClient();

var response =  client.GetAsync(uri).Result;
var documents =  response.Content.ReadAsAsync<IEnumerable<DocumentDto>>().Result;

我不喜欢这条线:

 Uri uri = new Uri(ConfigurationManager.AppSettings["ServiceUrl"] + "/api/document/GetByDate?date=" + date;

如果我明天将方法的名称更改为GetDocByDate,那么我将不得不回忆我在哪里使用过该方法并进行更改。你怎么解决这个问题?

4

1 回答 1

2

我有一个更好的方法IMO。使用此WebApiDoodle.Net.Http.Client NuGet 包,您可以执行以下操作:

public class ShipmentsClient : HttpApiClient<ShipmentDto>, IShipmentsClient {

      private const string BaseUriTemplateForSingle = "api/affiliates/{key}/shipments/{shipmentKey}";
      private readonly string _affiliateKey;

      public ShipmentsClient(HttpClient httpClient, string affiliateKey)
          : base(httpClient, MediaTypeFormatterCollection.Instance) {

          if (string.IsNullOrEmpty(affiliateKey)) {

              throw new ArgumentException("The argument 'affiliateKey' is null or empty.", "affiliateKey");
          }

          _affiliateKey = affiliateKey;
      }

      public async Task<ShipmentDto> GetShipmentAsync(Guid shipmentKey, string foo) {

          // this will build you the following URI:
          // HttpClient.BaseAddress + api/affiliates/" + _affiliateKey + "/shipments/" + shipmentKey + "?=foo" + foo
          var parameters = new { key = _affiliateKey, shipmentKey = shipmentKey, foo = foo };
          var responseTask = base.GetSingleAsync(BaseUriTemplateForSingle, parameters);
          var shipment = await HandleResponseAsync(responseTask);
          return shipment;
      }

      // Lines removed for brevity
}

此处提供了一个示例用例:https ://github.com/tugberkugurlu/PingYourPackage

对于您的其他问题(我假设您正在公开 RPC 样式 API),您可以使用以下命令设置方法的操作名称System.Web.Http.ActionNameAttribute

[ActionName("GetDocByDate")]
public IEnumerable<Car> Get() {

    IEnumerable<Car> cars = _carRepository.GetAll().ToList();
    return cars;
}
于 2013-03-28T07:15:04.623 回答