user348173
user348173

Reputation: 9278

flexible way to build uri to web api

I'm a novice in ASP.NET Web API and I have a question. I am calling the API in the following way:

 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;

I don't like this line:

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

What if I change tomorrow the name of a method to GetDocByDate, then I will have to recall where I have used this method and change. How do you solve this problem?

Upvotes: 0

Views: 250

Answers (1)

tugberk
tugberk

Reputation: 58444

I have a slightly better approach IMO. With this WebApiDoodle.Net.Http.Client NuGet package, you can do the following:

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
}

A sample use case is available here: https://github.com/tugberkugurlu/PingYourPackage

For your other problem (and I'm assuming you are exposing an RPC style API), you can set the action name of the method with the System.Web.Http.ActionNameAttribute:

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

    IEnumerable<Car> cars = _carRepository.GetAll().ToList();
    return cars;
}

Upvotes: 2

Related Questions