如安在Asp.Net Core中集成Refit(3)

public IServiceProvider ConfigureServices(IServiceCollection services) {           //dcs.part处事           services.AddHttpClient(PartsConsts.DcsPartClientName, config => {               config.BaseAddress = new Uri(_appConfiguration["DependencyServices:DcsParts"]);               config.Timeout = TimeSpan.FromSeconds(60);           });            }  

  这里我只是扼要截取了一小段内容,这里我们看到AddHttpClient的第一个参数也是一个字符串常量,这个常量应该是和IHttpClientFactory的CreateClient的要领中的谁人常量保持绝对的一致,只有这样我们才气够标识独一的标识一个HttpClient工具,建设完了之后我们就可以或许在这个内里去设置这个HttpClient的各类参数了,别的在上面的这段代码中_appConfiguration这个工具是通过Startup的结构函数注入的,详细的代码请参考下面。

public Startup(IHostingEnvironment env) {             _appConfiguration = env.GetAppConfiguration();             Clock.Provider = ClockProviders.Local;             Environment = env;             Console.OutputEncoding = System.Text.Encoding.UTF8;         }  

  别的我们还需要设置一些HttpClient所必需的属性包罗基地点、超时时间......等等,虽然这个基地点我们是设置在appsetting.json中的,详细的设置如下所示。

"DependencyServices": {    "BlobStorage": "http://blob-storage/",    "DcsParts": "http://dcs-parts/",    "DmsAfterSales": "http://dms-after-sales/"  }

  有了这些我们就可以或许具备建设一个HttpClient工具的条件了,后头我们来看看我们怎么利用这个HttpClient举办发送和吸收数据。

  1.3 HttpClient举办数据的发送和吸收

/// <summary>        /// Post请求返回实体        /// </summary>        /// <param>请求相对路径</param>        /// <param>请求数据</param>        /// <returns>实体T</returns>        public async Task<List<T>> PostResponse<T>(string relativeUrl, object postObj) where T : class {              var postData = JsonConvert.SerializeObject(postObj);              _httpClient.DefaultRequestHeaders.Add("user-agent", "Dcs-Parts");            _httpClient.CancelPendingRequests();            _httpClient.DefaultRequestHeaders.Clear();            HttpContent httpContent = new StringContent(postData);              httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");            var result = default(List<T>);            var response = await _httpClient.PostAsync(_httpClient.BaseAddress + relativeUrl, httpContent);            if (response.StatusCode == HttpStatusCode.NotFound) {                throw new ValidationException("找不到对应的DcsParts处事");            }            var responseContent = await response.Content.ReadAsAsync<ReceiveResponseBody<List<T>>>();            if (response.IsSuccessStatusCode) {                result = responseContent?.Payload;            } else {                if (!string.IsNullOrWhiteSpace(responseContent?.Message)) {                    throw new ValidationException(responseContent.Message);                }                  _loggerHelper.LogDebug($"请求返回功效:{0} 请求内容:{1}", response.StatusCode, postData);            }              return await Task.FromResult(result);        }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wsjjpz.html