我是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
,那么我将不得不回想一下我使用此方法的位置并进行更改。你是如何解决这个问题的?
答案 0 :(得分: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;
}