public void QueryStringWithEnumerablesCanBeFormattedEnumerable() { var settings = new RefitSettings { UrlParameterFormatter = new TestEnumerableUrlParameterFormatter() }; var fixture = new RequestBuilderImplementation(typeof(IDummyHttpApi), settings); var factory = fixture.BuildRequestFactoryForMethod("QueryWithEnumerable"); var list = new List <int> { 1, 2, 3 }; var output = factory(new object[] { list }); var uri = new Uri(new Uri("http://api"), output.RequestUri); Assert.Equal("/query?numbers=1%2C2%2C3", uri.PathAndQuery); }
public async Task HitTheNpmJs() { var mockHttp = new MockHttpMessageHandler(); var settings = new RefitSettings { HttpMessageHandlerFactory = () => mockHttp }; mockHttp.Expect(HttpMethod.Get, "https://registry.npmjs.org/congruence") .Respond("application/json", "{ '_id':'congruence', '_rev':'rev' , 'name':'name'}"); var fixture = RestService.For <INpmJs>("https://registry.npmjs.org", settings); var result = await fixture.GetCongruence(); Assert.Equal("congruence", result._id); mockHttp.VerifyNoOutstandingExpectation(); }
public async Task GenericMethodOverloadTest4() { var mockHttp = new MockHttpMessageHandler(); var settings = new RefitSettings { HttpMessageHandlerFactory = () => mockHttp }; mockHttp.Expect(HttpMethod.Get, "https://httpbin.org/get") .WithHeaders("X-Refit", "99") .WithQueryString("param", "foo") .Respond("application/json", "{'url': 'https://httpbin.org/get', 'args': {'param': 'foo'}}"); var fixture = RestService.For <IUseOverloadedGenericMethods <HttpBinGet, string, int> >("https://httpbin.org/", settings); var result = await fixture.Get("foo", 99); Assert.Equal("foo", result.Args["param"]); }
public async Task GenericMethodOverloadTest2() { var mockHttp = new MockHttpMessageHandler(); var settings = new RefitSettings { HttpMessageHandlerFactory = () => mockHttp }; mockHttp.Expect(HttpMethod.Get, "https://httpbin.org/status/403") .Respond(HttpStatusCode.Forbidden); var fixture = RestService.For <IUseOverloadedGenericMethods <HttpBinGet, string, int> >("https://httpbin.org/", settings); var resp = await fixture.Get(403); Assert.Equal(HttpStatusCode.Forbidden, resp.StatusCode); }
public async Task PostStringDefaultToRequestBin() { var mockHttp = new MockHttpMessageHandler(); var settings = new RefitSettings { HttpMessageHandlerFactory = () => mockHttp }; mockHttp.Expect(HttpMethod.Post, "http://httpbin.org/foo") .WithContent("raw string") .Respond(HttpStatusCode.OK); var fixture = RestService.For <IRequestBin>("http://httpbin.org/", settings); await fixture.PostRawStringDefault("raw string"); mockHttp.VerifyNoOutstandingExpectation(); }
public async Task GenericMethodOverloadTest3() { var mockHttp = new MockHttpMessageHandler(); var settings = new RefitSettings { HttpMessageHandlerFactory = () => mockHttp }; mockHttp.Expect(HttpMethod.Get, "https://httpbin.org/get") .WithQueryString("someVal", "201") .Respond("application/json", "some-T-value"); var fixture = RestService.For <IUseOverloadedGenericMethods <HttpBinGet, string, int> >("https://httpbin.org/", settings); var result = await fixture.Get <string>(201); Assert.Equal("some-T-value", result); }
public CertifyClient( string apiKey, string apiSecret, CertifyClientOptions?options = null) { options ??= new(); var refitSettings = new RefitSettings { ContentSerializer = new NewtonsoftJsonContentSerializer( new JsonSerializerSettings { MissingMemberHandling = MissingMemberHandling.Ignore, }), }; _httpClient = new HttpClient( new AuthenticatedHttpClientHandler( apiKey ?? throw new ArgumentNullException(nameof(apiKey)), apiSecret ?? throw new ArgumentNullException(nameof(apiSecret)) )) { // This address should NOT end in "/" as the interface method paths are added to the end of this and Refit requires they start with "/" BaseAddress = new Uri("https://api.certify.com/v1"), Timeout = options.Timeout }; CpdLists = RestService.For <ICpdLists>(_httpClient, refitSettings); Departments = RestService.For <IDepartments>(_httpClient, refitSettings); EmpGlds = RestService.For <IEmpGlds>(_httpClient, refitSettings); ExpenseCategories = RestService.For <IExpenseCategories>(_httpClient, refitSettings); ExpenseReports = RestService.For <IExpenseReports>(_httpClient, refitSettings); Expenses = RestService.For <IExpenses>(_httpClient, refitSettings); ExpenseReportGlds = RestService.For <IExpenseReportGlds>(_httpClient, refitSettings); InvoiceReports = RestService.For <IInvoiceReports>(_httpClient, refitSettings); Invoices = RestService.For <IInvoices>(_httpClient, refitSettings); MileageRates = RestService.For <IMileageRates>(_httpClient, refitSettings); MileageRateDetails = RestService.For <IMileageRateDetails>(_httpClient, refitSettings); Receipts = RestService.For <IReceipts>(_httpClient, refitSettings); Users = RestService.For <IUsers>(_httpClient, refitSettings); }
public async Task GenericMethodOverloadTest() { var mockHttp = new MockHttpMessageHandler(); var settings = new RefitSettings { HttpMessageHandlerFactory = () => mockHttp }; mockHttp.Expect(HttpMethod.Get, "https://httpbin.org/") .Respond(HttpStatusCode.OK, "text/html", "OK"); mockHttp.Expect(HttpMethod.Get, "https://httpbin.org/status/403") .Respond(HttpStatusCode.Forbidden); mockHttp.Expect(HttpMethod.Get, "https://httpbin.org/get") .WithHeaders("X-Refit", "99") .WithQueryString("param", "foo") .Respond("application/json", "{'url': 'https://httpbin.org/get', 'args': {'param': 'foo'}}"); mockHttp.Expect(HttpMethod.Get, "https://httpbin.org/get") .WithHeaders("X-Refit", "foo") .WithQueryString("param", "99") .Respond("application/json", "{'url': 'https://httpbin.org/get', 'args': {'param': '99'}}"); var fixture = RestService.For <IUseOverloadedGenericMethods <HttpBinGet, string, int> >("https://httpbin.org/", settings); var plainText = await fixture.Get(); var resp = await fixture.Get(403); var result = await fixture.Get("foo", 99); var result2 = await fixture.Get(99, "foo"); Assert.True(!String.IsNullOrWhiteSpace(plainText)); Assert.Equal(HttpStatusCode.Forbidden, resp.StatusCode); Assert.Equal("foo", result.Args["param"]); Assert.Equal("99", result2.Args["param"]); }
public static IHttpClientBuilder AddApiClient <T>(this IServiceCollection services, Action <HttpClient> configureClient) where T : class { var refitSettings = new RefitSettings { ContentSerializer = new JsonContentSerializer( new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, ContractResolver = new CamelCasePropertyNamesContractResolver() }) }; if (!services.Any(svc => svc.ImplementationType == typeof(HttpLoggingHandler))) { services.AddTransient <HttpLoggingHandler>(); } return(services.AddRefitClient <T>(refitSettings) .ConfigureHttpClient(configureClient) .AddHttpMessageHandler <HttpLoggingHandler>()); }
public async Task PostToRequestBin() { var mockHttp = new MockHttpMessageHandler(); var settings = new RefitSettings { HttpMessageHandlerFactory = () => mockHttp }; mockHttp.Expect(HttpMethod.Post, "http://httpbin.org/1h3a5jm1") .Respond(HttpStatusCode.OK); var fixture = RestService.For <IRequestBin>("http://httpbin.org/", settings); try { await fixture.Post(); } catch (ApiException ex) { // we should be good but maybe a 404 occurred } mockHttp.VerifyNoOutstandingExpectation(); }
public async Task PostStringUrlToRequestBin() { var mockHttp = new MockHttpMessageHandler(); var settings = new RefitSettings { HttpMessageHandlerFactory = () => mockHttp }; mockHttp.Expect(HttpMethod.Post, "http://httpbin.org/foo") .WithContent("url%26string") .WithHeaders("Content-Type", "application/x-www-form-urlencoded; charset=utf-8") .Respond(HttpStatusCode.OK); var fixture = RestService.For <IRequestBin>("http://httpbin.org/", settings); await fixture.PostRawStringUrlEncoded("url&string"); mockHttp.VerifyNoOutstandingExpectation(); }
public async Task GetWithDecimal() { var mockHttp = new MockHttpMessageHandler(); var settings = new RefitSettings { HttpMessageHandlerFactory = () => mockHttp }; mockHttp.Expect(HttpMethod.Get, "http://foo/withDecimal") .WithExactQueryString(new[] { new KeyValuePair <string, string>("value", "3.456") }) .Respond("application/json", "Ok"); var fixture = RestService.For <IApiWithDecimal>("http://foo", settings); const decimal val = 3.456M; var result = await fixture.GetWithDecimal(val); mockHttp.VerifyNoOutstandingExpectation(); }
public async Task ServiceOutsideNamespaceGetRequest() { var mockHttp = new MockHttpMessageHandler(); var settings = new RefitSettings { HttpMessageHandlerFactory = () => mockHttp }; mockHttp.Expect(HttpMethod.Get, "http://foo/") // We can't add HttpContent to a GET request, // because HttpClient doesn't allow it and it will // blow up at runtime .With(r => r.Content == null) .Respond("application/json", "Ok"); var fixture = RestService.For <IServiceWithoutNamespace>("http://foo", settings); await fixture.GetRoot(); mockHttp.VerifyNoOutstandingExpectation(); }
public async Task DoesntAddAutoAddContentToHeadRequest() { var mockHttp = new MockHttpMessageHandler(); var settings = new RefitSettings { HttpMessageHandlerFactory = () => mockHttp }; mockHttp.Expect(HttpMethod.Head, "http://foo/nobody") // We can't add HttpContent to a HEAD request, // because HttpClient doesn't allow it and it will // blow up at runtime .With(r => r.Content == null) .Respond("application/json", "Ok"); var fixture = RestService.For <IBodylessApi>("http://foo", settings); await fixture.Head(); mockHttp.VerifyNoOutstandingExpectation(); }
/// <summary> /// 封装Refit,默认将Cookie添加到Header中 /// </summary> /// <typeparam name="TInterface"></typeparam> /// <param name="services"></param> /// <param name="host"></param> /// <returns></returns> private static IServiceCollection AddBiliBiliClientApi <TInterface>(this IServiceCollection services, string host) where TInterface : class { var settings = new RefitSettings(new SystemTextJsonContentSerializer(JsonSerializerOptionsBuilder.DefaultOptions)); services.AddRefitClient <TInterface>(settings) .ConfigureHttpClient((sp, c) => { c.DefaultRequestHeaders.Add("Cookie", sp.GetRequiredService <IOptionsMonitor <BiliBiliCookieOptions> >().CurrentValue.ToString()); c.DefaultRequestHeaders.Add("User-Agent", sp.GetRequiredService <IOptionsMonitor <SecurityOptions> >().CurrentValue.UserAgent); c.BaseAddress = new Uri(host); }) .AddHttpMessageHandler(sp => new MyHttpClientDelegatingHandler( sp.GetRequiredService <ILogger <MyHttpClientDelegatingHandler> >(), sp.GetRequiredService <IOptionsMonitor <SecurityOptions> >() )); return(services); }
public void UpdateApiUrl(string newApiUrl) { // TODO: As you go through and implement the various APIs, update these from the fake to the real ProfilesAPI = new FakeProfilesAPI(); HomeAPI = new FakeHomeAPI(); LoginAPI = new FakeLoginAPI(); //ProfilesAPI = RestService.For<IProfilesAPI>(HttpClientFactory.Create(newApiUrl)); //HomeAPI = RestService.For<IHomeAPI>(HttpClientFactory.Create(newApiUrl)); var productsRefitSettings = new RefitSettings { ContentSerializer = new JsonContentSerializer(ProductPerDTOJsonConverter.Settings) }; ProductsAPI = RestService.For <IProductsAPI>(HttpClientFactory.Create(newApiUrl), productsRefitSettings); //LoginAPI = RestService.For<ILoginAPI>(HttpClientFactory.Create(newApiUrl)); }
public async void AuthenticatedHandlerUsesAuth() { var handler = new MockHttpMessageHandler(); var settings = new RefitSettings() { AuthorizationHeaderValueGetter = () => Task.FromResult("tokenValue"), HttpMessageHandlerFactory = () => handler }; handler.Expect(HttpMethod.Get, "http://api/auth") .WithHeaders("Authorization", "Bearer tokenValue") .Respond("text/plain", "Ok"); var fixture = RestService.For <IMyAuthenticatedService>("http://api", settings); var result = await fixture.GetAuthenticated(); handler.VerifyNoOutstandingExpectation(); Assert.Equal("Ok", result); }
public async Task ProvideFactoryWhichAlwaysReturnsException_WithoutResult() { var handler = new MockHttpMessageHandler(); var exception = new Exception("I like to fail"); var settings = new RefitSettings() { HttpMessageHandlerFactory = () => handler, ExceptionFactory = _ => Task.FromResult <Exception>(exception) }; handler.Expect(HttpMethod.Put, "http://api/put-without-result") .Respond(HttpStatusCode.OK); var fixture = RestService.For <IMyService>("http://api", settings); var thrownException = await Assert.ThrowsAsync <Exception>(() => fixture.PutWithoutResult()); Assert.Equal(exception, thrownException); handler.VerifyNoOutstandingExpectation(); }
/// <summary> /// Adds a Refit client for <see cref="TClient"/> and automatically applies the /// options for <typeparamref name="TOptions"/>. /// <see cref="HttpClientBuilderExtensions.ConfigureWithOptions"/> for more information. /// </summary> /// <typeparam name="TClient">The Refit Client interface.</typeparam> /// <typeparam name="TOptions">The type of <see cref="HttpClientOptions"/>.</typeparam> /// <param name="services">The <see cref="IServiceCollection"/>.</param> /// <param name="configuration">The <see cref="IConfiguration"/>.</param> /// <param name="key"> /// The configuration section key name to use. /// If not provided, it will be the <typeparamref name="T"/> type name without the -Options prefix. /// (see <see cref="ConfigurationExtensions.DefaultOptionsName(Type)"/>. /// </param> /// <param name="refitSettings"> /// Custom <see cref="RefitSettings"/> to apply, if any.</param> /// <returns>The configured <see cref="IHttpClientBuilder"/>, that can be further customized.</returns> public static IHttpClientBuilder AddRefitClient <TClient, TOptions>( this IServiceCollection services, IConfiguration configuration, string?key = null, RefitSettings?refitSettings = null) where TClient : class where TOptions : HttpClientOptions, new() { services.BindOptionsToConfigurationAndValidate <TOptions>(configuration, key: key); var options = configuration.ReadOptionsAndValidate <TOptions>(key); if (refitSettings is null) { if ("xml".Equals(options.Serializer, StringComparison.OrdinalIgnoreCase)) { refitSettings = new RefitSettings(new XmlContentSerializer()); } else { var jsonSerializerOptions = new JsonSerializerOptions { IgnoreNullValues = true, PropertyNameCaseInsensitive = true, WriteIndented = true, }; jsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()); jsonSerializerOptions.Converters.Add(new JsonTimeSpanConverter()); jsonSerializerOptions.Converters.Add(new JsonNullableTimeSpanConverter()); refitSettings = new RefitSettings(new SystemTextJsonContentSerializer(jsonSerializerOptions)); } } return(services .AddSingleton(provider => RequestBuilder.ForType <TClient>(refitSettings)) .AddHttpClient(typeof(TClient).Name) .ConfigureWithOptions <TOptions>(configuration, key: key) .AddTypedClient((client, serviceProvider) => RestService.For(client, serviceProvider.GetService <IRequestBuilder <TClient> >()))); }
public async Task MultipartUploadShouldWorkWithAnObject(Type contentSerializerType, string mediaType) { if (!(Activator.CreateInstance(contentSerializerType) is IContentSerializer serializer)) { throw new ArgumentException($"{contentSerializerType.FullName} does not implement {nameof(IContentSerializer)}"); } var model1 = new ModelObject { Property1 = "M1.prop1", Property2 = "M1.prop2" }; var handler = new MockHttpMessageHandler { Asserts = async content => { var parts = content.ToList(); Assert.Single(parts); Assert.Equal("theObject", parts[0].Headers.ContentDisposition.Name); Assert.Null(parts[0].Headers.ContentDisposition.FileName); Assert.Equal(mediaType, parts[0].Headers.ContentType.MediaType); var result0 = await serializer.DeserializeAsync <ModelObject>(parts[0]).ConfigureAwait(false); Assert.Equal(model1.Property1, result0.Property1); Assert.Equal(model1.Property2, result0.Property2); } }; var settings = new RefitSettings() { HttpMessageHandlerFactory = () => handler, ContentSerializer = serializer }; var fixture = RestService.For <IRunscopeApi>(BaseAddress, settings); var result = await fixture.UploadJsonObject(model1); }
public async Task HitTheGitHubUserApiAsObservableApiResponse() { var mockHttp = new MockHttpMessageHandler(); var settings = new RefitSettings { HttpMessageHandlerFactory = () => mockHttp, ContentSerializer = new JsonContentSerializer(new JsonSerializerSettings() { ContractResolver = new SnakeCasePropertyNamesContractResolver() }) }; var responseMessage = new HttpResponseMessage() { StatusCode = HttpStatusCode.OK, Content = new StringContent("{ 'login':'******', 'avatar_url':'http://foo/bar' }", System.Text.Encoding.UTF8, "application/json"), }; responseMessage.Headers.Add("Cookie", "Value"); mockHttp.Expect(HttpMethod.Get, "https://api.github.com/users/octocat").Respond(req => responseMessage); var fixture = RestService.For <IGitHubApi>("https://api.github.com", settings); var result = await fixture.GetUserObservableWithMetadata("octocat") .Timeout(TimeSpan.FromSeconds(10)); Assert.True(result.Headers.Any()); Assert.True(result.IsSuccessStatusCode); Assert.NotNull(result.ReasonPhrase); Assert.NotNull(result.RequestMessage); Assert.False(result.StatusCode == default); Assert.NotNull(result.Version); Assert.Equal("octocat", result.Content.Login); Assert.False(string.IsNullOrEmpty(result.Content.AvatarUrl)); mockHttp.VerifyNoOutstandingExpectation(); }
public MtDataReaderClient(string url, string apiKey, string userAgent) { var httpMessageHandler = new ApiKeyHeaderHttpClientHandler( new UserAgentHeaderHttpClientHandler( new RetryingHttpClientHandler(new HttpClientHandler(), 6, TimeSpan.FromSeconds(5)), userAgent), apiKey); var settings = new RefitSettings { HttpMessageHandlerFactory = () => httpMessageHandler }; AssetPairsRead = AddCaching(RestService.For <IAssetPairsReadingApi>(url, settings)); AccountHistory = RestService.For <IAccountHistoryApi>(url, settings); AccountsApi = RestService.For <IAccountsApi>(url, settings); AccountAssetPairsRead = RestService.For <IAccountAssetPairsReadingApi>(url, settings); TradeMonitoringRead = RestService.For <ITradeMonitoringReadingApi>(url, settings); TradingConditionsRead = RestService.For <ITradingConditionsReadingApi>(url, settings); AccountGroups = RestService.For <IAccountGroupsReadingApi>(url, settings); Dictionaries = RestService.For <IDictionariesReadingApi>(url, settings); Routes = RestService.For <IRoutesReadingApi>(url, settings); Settings = RestService.For <ISettingsReadingApi>(url, settings); }
public MarketPlaceClient(string baseEndPoint, Information info, Func <Task <string> > authorizationHeaderValueGetter, HttpMessageHandler innerHandler = null) { MarketPlaceHttpHeaders marketPlaceHttpHeaders = new MarketPlaceHttpHeaders(info); RefitSettings refitSetting = new RefitSettings { HttpMessageHandlerFactory = () => new MetricHttpHandler(new MarketPlaceHeadersHandler(marketPlaceHttpHeaders, innerHandler)), JsonSerializerSettings = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }, AuthorizationHeaderValueGetter = authorizationHeaderValueGetter }; _apiClient = RestService.For <IMarketPlaceClient>(baseEndPoint, refitSetting); //var httpHandler = new HttpClientHandler(); //httpHandler.Proxy = new WebProxy("http://192.168.1.9:9000"); //var httpClient = new HttpClient(httpHandler); //httpClient.BaseAddress = new Uri(baseEndPoint); // // //_apiClient = RestService.For<IMarketPlaceClient>(httpClient, refitSetting); }
public async Task ShouldRetHttpResponseMessage() { var mockHttp = new MockHttpMessageHandler(); var settings = new RefitSettings { HttpMessageHandlerFactory = () => mockHttp, JsonSerializerSettings = new JsonSerializerSettings() { ContractResolver = new SnakeCasePropertyNamesContractResolver() } }; mockHttp.When(HttpMethod.Get, "https://api.github.com/") .Respond(HttpStatusCode.OK); var fixture = RestService.For <IGitHubApi>("https://api.github.com", settings); var result = await fixture.GetIndex(); Assert.NotNull(result); Assert.True(result.IsSuccessStatusCode); }
public Client(string rootUrl, JsonSerializerOptions jsonSerializerOptions) { var settings = new RefitSettings(new SystemTextJsonContentSerializer(jsonSerializerOptions)); RepositoryDataApi = RestService.For <IRepositoryDataApi>(rootUrl, settings); AccountTokenHistoryApi = RestService.For <IAccountTokenHistoryApi>(rootUrl, settings); ConnectionUrlHistoryApi = RestService.For <IConnectionUrlHistoryApi>(rootUrl, settings); KeyValuesApi = RestService.For <IKeyValuesApi>(rootUrl, settings); KeyValuesHistoryApi = RestService.For <IKeyValuesHistoryApi>(rootUrl, settings); LocksApi = RestService.For <ILocksApi>(rootUrl, settings); NetworksApi = RestService.For <INetworksApi>(rootUrl, settings); RepositoriesApi = RestService.For <IRepositoriesApi>(rootUrl, settings); RepositoriesUpdateHistoryApi = RestService.For <IRepositoriesUpdateHistoryApi>(rootUrl, settings); RolesApi = RestService.For <IRolesApi>(rootUrl, settings); SecretKeyValuesApi = RestService.For <ISecretKeyValuesApi>(rootUrl, settings); ServiceTokenHistoryApi = RestService.For <IServiceTokenHistoryApi>(rootUrl, settings); ServiceTokensApi = RestService.For <IServiceTokensApi>(rootUrl, settings); TokensApi = RestService.For <ITokensApi>(rootUrl, settings); UserActionsHistoryApi = RestService.For <IUserActionsHistoryApi>(rootUrl, settings); UsersApi = RestService.For <IUsersApi>(rootUrl, settings); UserSignInHistoryApi = RestService.For <IUserSignInHistoryApi>(rootUrl, settings); }
/// <summary> /// 注册Rpc服务(跨服务之间的同步通讯) /// </summary> /// <typeparam name="TRpcService">Rpc服务接口</typeparam> /// <param name="serviceName">在注册中心注册的服务名称,或者服务的Url</param> /// <param name="policies">Polly策略</param> /// <param name="token">Token,可空</param> protected virtual void AddRpcService <TRpcService>(string serviceName , List <IAsyncPolicy <HttpResponseMessage> > policies , Func <Task <string> > token = null ) where TRpcService : class, IRpcService { var prefix = serviceName.Substring(0, 7); bool isConsulAdderss = (prefix == "http://" || prefix == "https:/") ? false : true; var refitSettings = new RefitSettings(new SystemTextJsonContentSerializer(SystemTextJsonHelper.GetAdncDefaultOptions())); //注册RefitClient,设置httpclient生命周期时间,默认也是2分钟。 var clientbuilder = _services.AddRefitClient <TRpcService>(refitSettings) .SetHandlerLifetime(TimeSpan.FromMinutes(2)); //从consul获取地址 if (isConsulAdderss) { clientbuilder.ConfigureHttpClient(c => c.BaseAddress = new Uri($"http://{serviceName}")) .AddHttpMessageHandler(() => { return(new ConsulDiscoveryDelegatingHandler(_consulConfig.ConsulUrl, token)); }); } else { clientbuilder.ConfigureHttpClient((options) => { options.BaseAddress = new Uri(serviceName); }); } //添加polly相关策略 if (policies != null && policies.Any()) { foreach (var policy in policies) { clientbuilder.AddPolicyHandler(policy); } } }
public static void AddDotnetWebApiBenchApiRefitClients(this IServiceCollection services, string apiAddress, bool allowInvalidCerts = false) { services.AddTransient <AuthenticationHandler>(ctx => new AuthenticationHandler(apiAddress)); RefitSettings refitSettings = new RefitSettings() { ContentSerializer = new NewtonsoftJsonContentSerializer() }; List <IHttpClientBuilder> httpClientBuilders = new List <IHttpClientBuilder>(); httpClientBuilders.Add(services.AddRefitClient <IProductsClient>(refitSettings)); httpClientBuilders.Add(services.AddRefitClient <IOrdersClient>(refitSettings)); httpClientBuilders.Add(services.AddRefitClient <ICustomersClient>(refitSettings)); httpClientBuilders.Add(services.AddRefitClient <IHeartbeatClient>(refitSettings)); foreach (IHttpClientBuilder clientBuilder in httpClientBuilders) { clientBuilder.ConfigureHttpClient((client) => { client.BaseAddress = new Uri(apiAddress); }) .AddHttpMessageHandler <AuthenticationHandler>(); if (allowInvalidCerts) { var noSslCheckHandler = new HttpClientHandler(); noSslCheckHandler.ClientCertificateOptions = ClientCertificateOption.Manual; noSslCheckHandler.UseProxy = false; noSslCheckHandler.ServerCertificateCustomValidationCallback = (httpRequestMessage, cert, cetChain, policyErrors) => { return(true); }; clientBuilder.ConfigurePrimaryHttpMessageHandler(() => noSslCheckHandler); } } }
public async Task ComplexDynamicQueryparametersTest() { var mockHttp = new MockHttpMessageHandler(); var settings = new RefitSettings { HttpMessageHandlerFactory = () => mockHttp }; mockHttp.Expect(HttpMethod.Get, "https://httpbin.org/get") .Respond("application/json", "{'url': 'https://httpbin.org/get?hardcoded=true&FirstName=John&LastName=Rambo&Addr_Zip=9999&Addr_Street=HomeStreet 99&MetaData_Age=99&MetaData_Initials=JR&MetaData_Birthday=10%2F31%2F1918 4%3A21%3A16 PM&Other=12345&Other=10%2F31%2F2017 4%3A21%3A17 PM&Other=696e8653-6671-4484-a65f-9485af95fd3a', 'args': { 'Addr_Street': 'HomeStreet 99', 'Addr_Zip': '9999', 'FirstName': 'John', 'LastName': 'Rambo', 'MetaData_Age': '99', 'MetaData_Birthday': '10/31/1981 4:32:59 PM', 'MetaData_Initials': 'JR', 'Other': ['12345','10/31/2017 4:32:59 PM','60282dd2-f79a-4400-be01-bcb0e86e7bc6'], 'hardcoded': 'true'}}"); var myParams = new MyComplexQueryParams { FirstName = "John", LastName = "Rambo" }; myParams.Address.Postcode = 9999; myParams.Address.Street = "HomeStreet 99"; myParams.MetaData.Add("Age", 99); myParams.MetaData.Add("Initials", "JR"); myParams.MetaData.Add("Birthday", new DateTime(1981, 10, 31, 16, 24, 59)); myParams.Other.Add(12345); myParams.Other.Add(new DateTime(2017, 10, 31, 16, 24, 59)); myParams.Other.Add(new Guid("60282dd2-f79a-4400-be01-bcb0e86e7bc6")); var fixture = RestService.For <IHttpBinApi <HttpBinGet, MyComplexQueryParams, int> >("https://httpbin.org", settings); var resp = await fixture.GetQuery(myParams); Assert.Equal("John", resp.Args["FirstName"]); Assert.Equal("Rambo", resp.Args["LastName"]); Assert.Equal("9999", resp.Args["Addr_Zip"]); }
public static void Configure(IConfiguration configuration, IServiceCollection services) { var funzaSettings = configuration.GetSection("FunzaSettings").Get <FunzaSettings>(); var settings = new RefitSettings(); services.AddRefitClient <IInternalSecurityClient>() .ConfigureHttpClient(c => { c.BaseAddress = new Uri(new Uri(funzaSettings.FunzaUrl), "security"); //var policies = new IAsyncPolicy[] { // c.CustomRefreshTokenConfiguration(), // c.CustomLoggingConfiguration() //}; //(c as CustomHttpClient).Policies = Policy.WrapAsync(policies); }); services.AddRefitClient <IInternalQuoteClient>() .AddTypedClient <CustomHttpClient>(c => new CustomHttpClient()) .ConfigureHttpClient(c => { c.BaseAddress = new Uri(new Uri(funzaSettings.FunzaUrl), "quotes"); //var policies = new IAsyncPolicy[] { // c.CustomRefreshTokenConfiguration(), // c.CustomLoggingConfiguration() //}; //(c as CustomHttpClient).Policies = Policy.WrapAsync(policies); }); services.AddRefitClient <IInternalSyncClient>() .AddTypedClient <CustomHttpClient>(c => new CustomHttpClient()) .ConfigureHttpClient(c => { c.BaseAddress = new Uri(new Uri(funzaSettings.FunzaUrl), "sync"); }); }
public static void InitiateRefitServices(this IServiceCollection services, IConfiguration configuration) { var appSettingsOption = configuration.Get <Settings>(); var settings = new RefitSettings { }; services.AddRefitClient <IUserApi>(settings) .ConfigureHttpClient(c => { c.BaseAddress = new Uri(appSettingsOption.RefitUrls.UserApi); }); services.AddRefitClient <IPatientApi>(settings) .ConfigureHttpClient(c => { c.BaseAddress = new Uri(appSettingsOption.RefitUrls.PatientApi); }); services.AddRefitClient <IClinicApi>(settings) .ConfigureHttpClient(c => { c.BaseAddress = new Uri(appSettingsOption.RefitUrls.ClinicApi); }); services.AddRefitClient <IConsultationApi>(settings) .ConfigureHttpClient(c => { c.BaseAddress = new Uri(appSettingsOption.RefitUrls.ConsultationApi); }); services.AddRefitClient <IAppointmentApi>(settings) .ConfigureHttpClient(c => { c.BaseAddress = new Uri(appSettingsOption.RefitUrls.AppointmentApi); }); }
public async Task CustomParmeterFormatter() { var settings = new RefitSettings { UrlParameterFormatter = new TestUrlParameterFormatter("custom-parameter") }; var fixture = new RequestBuilderImplementation(typeof(IDummyHttpApi), settings); var factory = fixture.BuildRequestFactoryForMethod("FetchSomeStuff"); var output = factory(new object[] { 5 }); var uri = new Uri(new Uri("http://api"), output.RequestUri); Assert.AreEqual("/foo/bar/custom-parameter", uri.PathAndQuery); }