Skip to content

Commit 2e4ce2c

Browse files
author
liguoliang
committed
添加client时注册path
1 parent 8b441ed commit 2e4ce2c

2 files changed

Lines changed: 29 additions & 3 deletions

File tree

src/DotNetCoreRpc.Client/ClientOptions.cs

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,11 @@ public class ClientOptions
1313
private IServiceCollection _services;
1414
private readonly string _serviceName;
1515

16+
/// <summary>
17+
/// 服务请求路径
18+
/// </summary>
19+
public string Path { get; set; }
20+
1621
public ClientOptions(IServiceCollection services, string serviceName)
1722
{
1823
_services = services;
@@ -24,7 +29,8 @@ public ClientOptions AddRpcClient<T>() where T : class
2429
_services.TryAddScoped(provider => {
2530
var httpClientFactory = provider.GetRequiredService<IHttpClientFactory>();
2631
var proxyGenerator = provider.GetRequiredService<ProxyGenerator>();
27-
RpcClient rpcClient = new RpcClient(httpClientFactory.CreateClient(_serviceName), proxyGenerator);
32+
var httpClient = httpClientFactory.CreateClient(_serviceName);
33+
RpcClient rpcClient = new RpcClient(httpClient, proxyGenerator, Path);
2834
return rpcClient.CreateClient<T>();
2935
});
3036
return this;
Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
using Castle.DynamicProxy;
22
using System;
33
using System.Collections.Generic;
4+
using System.IO;
45
using System.Net.Http;
56
using System.Text;
67

@@ -10,18 +11,37 @@ internal class RpcClient
1011
{
1112
private HttpClient _httpClient;
1213
private ProxyGenerator _proxyGenerator;
14+
private string _path;
1315

14-
public RpcClient(HttpClient httpClient, ProxyGenerator proxyGenerator)
16+
public RpcClient(HttpClient httpClient, ProxyGenerator proxyGenerator, string path)
1517
{
1618
_httpClient = httpClient;
17-
_httpClient.DefaultRequestHeaders.Add("req-source", "dncrpc");
1819
_proxyGenerator = proxyGenerator;
20+
_path = path;
1921
}
2022

2123
internal T CreateClient<T>() where T : class
2224
{
25+
InitalHttpClient();
26+
2327
HttpRequestInterceptor httpRequestInterceptor = new HttpRequestInterceptor(_httpClient);
2428
return _proxyGenerator.CreateInterfaceProxyWithoutTarget<T>(httpRequestInterceptor);
2529
}
30+
31+
private void InitalHttpClient()
32+
{
33+
_httpClient.DefaultRequestHeaders.Add("req-source", "dncrpc");
34+
if (!string.IsNullOrWhiteSpace(_path))
35+
{
36+
string path = _path;
37+
38+
if (_path.StartsWith("/"))
39+
{
40+
path = path.TrimStart('/');
41+
}
42+
43+
_httpClient.BaseAddress = new Uri(_httpClient.BaseAddress.ToString() + path);
44+
}
45+
}
2646
}
2747
}

0 commit comments

Comments
 (0)