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 に答える