├── .gitattributes
├── .gitignore
├── LICENSE
├── README.md
├── WebApiClient.Extensions.Autofac
├── AutofacExtensions.cs
├── AutofacServiceProvider.cs
├── HttpApiFactoryBuilder.cs
└── WebApiClient.Extensions.Autofac.csproj
├── WebApiClient.Extensions.DependencyInjection
├── DependencyInjectionExtensions.cs
├── HttpApiFactoryBuilder.cs
└── WebApiClient.Extensions.DependencyInjection.csproj
├── WebApiClient.Extensions.DiscoveryClient
├── DiscoveryClientExtensions.cs
└── WebApiClient.Extensions.DiscoveryClient.csproj
├── WebApiClient.Extensions.HttpClientFactory
├── HttpClientFactoryExtensions.cs
└── WebApiClient.Extensions.HttpClientFactory.csproj
├── WebApiClient.Extensions.JsonRpc
├── JsonRpc.cs
├── JsonRpcContent.cs
├── JsonRpcError.cs
├── JsonRpcException.cs
├── JsonRpcMethodAttribute.cs
├── JsonRpcParamsStyle.cs
├── JsonRpcRequest.cs
├── JsonRpcResult.cs
├── RpcParamAttribute.cs
└── WebApiClient.Extensions.JsonRpc.csproj
├── WebApiClient.Extensions.MessagePack
├── MessagePackContentAttribute.cs
├── MessagePackReturnAttribute.cs
└── WebApiClient.Extensions.MessagePack.csproj
├── WebApiClient.Extensions.Protobuf
├── ProtobufContentAttribute.cs
├── ProtobufReturnAttribute.cs
└── WebApiClient.Extensions.Protobuf.csproj
└── WebApiClient.Extensions.sln
/.gitattributes:
--------------------------------------------------------------------------------
1 | ###############################################################################
2 | # Set default behavior to automatically normalize line endings.
3 | ###############################################################################
4 | * text=auto
5 |
6 | ###############################################################################
7 | # Set default behavior for command prompt diff.
8 | #
9 | # This is need for earlier builds of msysgit that does not have it on by
10 | # default for csharp files.
11 | # Note: This is only used by command line
12 | ###############################################################################
13 | #*.cs diff=csharp
14 |
15 | ###############################################################################
16 | # Set the merge driver for project and solution files
17 | #
18 | # Merging from the command prompt will add diff markers to the files if there
19 | # are conflicts (Merging from VS is not affected by the settings below, in VS
20 | # the diff markers are never inserted). Diff markers may cause the following
21 | # file extensions to fail to load in VS. An alternative would be to treat
22 | # these files as binary and thus will always conflict and require user
23 | # intervention with every merge. To do so, just uncomment the entries below
24 | ###############################################################################
25 | #*.sln merge=binary
26 | #*.csproj merge=binary
27 | #*.vbproj merge=binary
28 | #*.vcxproj merge=binary
29 | #*.vcproj merge=binary
30 | #*.dbproj merge=binary
31 | #*.fsproj merge=binary
32 | #*.lsproj merge=binary
33 | #*.wixproj merge=binary
34 | #*.modelproj merge=binary
35 | #*.sqlproj merge=binary
36 | #*.wwaproj merge=binary
37 |
38 | ###############################################################################
39 | # behavior for image files
40 | #
41 | # image files are treated as binary by default.
42 | ###############################################################################
43 | #*.jpg binary
44 | #*.png binary
45 | #*.gif binary
46 |
47 | ###############################################################################
48 | # diff behavior for common document formats
49 | #
50 | # Convert binary document formats to text before diffing them. This feature
51 | # is only available from the command line. Turn it on by uncommenting the
52 | # entries below.
53 | ###############################################################################
54 | #*.doc diff=astextplain
55 | #*.DOC diff=astextplain
56 | #*.docx diff=astextplain
57 | #*.DOCX diff=astextplain
58 | #*.dot diff=astextplain
59 | #*.DOT diff=astextplain
60 | #*.pdf diff=astextplain
61 | #*.PDF diff=astextplain
62 | #*.rtf diff=astextplain
63 | #*.RTF diff=astextplain
64 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 |
4 | # User-specific files
5 | *.suo
6 | *.user
7 | *.userosscache
8 | *.sln.docstates
9 |
10 | # User-specific files (MonoDevelop/Xamarin Studio)
11 | *.userprefs
12 |
13 | # Build results
14 | [Dd]ebug/
15 | [Dd]ebugPublic/
16 | [Rr]elease/
17 | [Rr]eleases/
18 | x64/
19 | x86/
20 | bld/
21 | [Bb]in/
22 | [Oo]bj/
23 | [Ll]og/
24 |
25 | # Visual Studio 2015 cache/options directory
26 | .vs/
27 | # Uncomment if you have tasks that create the project's static files in wwwroot
28 | #wwwroot/
29 |
30 | # MSTest test Results
31 | [Tt]est[Rr]esult*/
32 | [Bb]uild[Ll]og.*
33 |
34 | # NUNIT
35 | *.VisualState.xml
36 | TestResult.xml
37 |
38 | # Build Results of an ATL Project
39 | [Dd]ebugPS/
40 | [Rr]eleasePS/
41 | dlldata.c
42 |
43 | # DNX
44 | project.lock.json
45 | project.fragment.lock.json
46 | artifacts/
47 |
48 | *_i.c
49 | *_p.c
50 | *_i.h
51 | *.ilk
52 | *.meta
53 | *.obj
54 | *.pch
55 | *.pdb
56 | *.pgc
57 | *.pgd
58 | *.rsp
59 | *.sbr
60 | *.tlb
61 | *.tli
62 | *.tlh
63 | *.tmp
64 | *.tmp_proj
65 | *.log
66 | *.vspscc
67 | *.vssscc
68 | .builds
69 | *.pidb
70 | *.svclog
71 | *.scc
72 |
73 | # Chutzpah Test files
74 | _Chutzpah*
75 |
76 | # Visual C++ cache files
77 | ipch/
78 | *.aps
79 | *.ncb
80 | *.opendb
81 | *.opensdf
82 | *.sdf
83 | *.cachefile
84 | *.VC.db
85 | *.VC.VC.opendb
86 |
87 | # Visual Studio profiler
88 | *.psess
89 | *.vsp
90 | *.vspx
91 | *.sap
92 |
93 | # TFS 2012 Local Workspace
94 | $tf/
95 |
96 | # Guidance Automation Toolkit
97 | *.gpState
98 |
99 | # ReSharper is a .NET coding add-in
100 | _ReSharper*/
101 | *.[Rr]e[Ss]harper
102 | *.DotSettings.user
103 |
104 | # JustCode is a .NET coding add-in
105 | .JustCode
106 |
107 | # TeamCity is a build add-in
108 | _TeamCity*
109 |
110 | # DotCover is a Code Coverage Tool
111 | *.dotCover
112 |
113 | # NCrunch
114 | _NCrunch_*
115 | .*crunch*.local.xml
116 | nCrunchTemp_*
117 |
118 | # MightyMoose
119 | *.mm.*
120 | AutoTest.Net/
121 |
122 | # Web workbench (sass)
123 | .sass-cache/
124 |
125 | # Installshield output folder
126 | [Ee]xpress/
127 |
128 | # DocProject is a documentation generator add-in
129 | DocProject/buildhelp/
130 | DocProject/Help/*.HxT
131 | DocProject/Help/*.HxC
132 | DocProject/Help/*.hhc
133 | DocProject/Help/*.hhk
134 | DocProject/Help/*.hhp
135 | DocProject/Help/Html2
136 | DocProject/Help/html
137 |
138 | # Click-Once directory
139 | publish/
140 |
141 | # Publish Web Output
142 | *.[Pp]ublish.xml
143 | *.azurePubxml
144 | # TODO: Comment the next line if you want to checkin your web deploy settings
145 | # but database connection strings (with potential passwords) will be unencrypted
146 | #*.pubxml
147 | *.publishproj
148 |
149 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
150 | # checkin your Azure Web App publish settings, but sensitive information contained
151 | # in these scripts will be unencrypted
152 | PublishScripts/
153 |
154 | # NuGet Packages
155 | *.nupkg
156 | # The packages folder can be ignored because of Package Restore
157 | **/packages/*
158 | # except build/, which is used as an MSBuild target.
159 | !**/packages/build/
160 | # Uncomment if necessary however generally it will be regenerated when needed
161 | #!**/packages/repositories.config
162 | # NuGet v3's project.json files produces more ignoreable files
163 | *.nuget.props
164 | *.nuget.targets
165 |
166 | # Microsoft Azure Build Output
167 | csx/
168 | *.build.csdef
169 |
170 | # Microsoft Azure Emulator
171 | ecf/
172 | rcf/
173 |
174 | # Windows Store app package directories and files
175 | AppPackages/
176 | BundleArtifacts/
177 | Package.StoreAssociation.xml
178 | _pkginfo.txt
179 |
180 | # Visual Studio cache files
181 | # files ending in .cache can be ignored
182 | *.[Cc]ache
183 | # but keep track of directories ending in .cache
184 | !*.[Cc]ache/
185 |
186 | # Others
187 | ClientBin/
188 | ~$*
189 | *~
190 | *.dbmdl
191 | *.dbproj.schemaview
192 | *.jfm
193 | *.pfx
194 | *.publishsettings
195 | node_modules/
196 | orleans.codegen.cs
197 |
198 | # Since there are multiple workflows, uncomment next line to ignore bower_components
199 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
200 | #bower_components/
201 |
202 | # RIA/Silverlight projects
203 | Generated_Code/
204 |
205 | # Backup & report files from converting an old project file
206 | # to a newer Visual Studio version. Backup files are not needed,
207 | # because we have git ;-)
208 | _UpgradeReport_Files/
209 | Backup*/
210 | UpgradeLog*.XML
211 | UpgradeLog*.htm
212 |
213 | # SQL Server files
214 | *.mdf
215 | *.ldf
216 |
217 | # Business Intelligence projects
218 | *.rdl.data
219 | *.bim.layout
220 | *.bim_*.settings
221 |
222 | # Microsoft Fakes
223 | FakesAssemblies/
224 |
225 | # GhostDoc plugin setting file
226 | *.GhostDoc.xml
227 |
228 | # Node.js Tools for Visual Studio
229 | .ntvs_analysis.dat
230 |
231 | # Visual Studio 6 build log
232 | *.plg
233 |
234 | # Visual Studio 6 workspace options file
235 | *.opt
236 |
237 | # Visual Studio LightSwitch build output
238 | **/*.HTMLClient/GeneratedArtifacts
239 | **/*.DesktopClient/GeneratedArtifacts
240 | **/*.DesktopClient/ModelManifest.xml
241 | **/*.Server/GeneratedArtifacts
242 | **/*.Server/ModelManifest.xml
243 | _Pvt_Extensions
244 |
245 | # Paket dependency manager
246 | .paket/paket.exe
247 | paket-files/
248 |
249 | # FAKE - F# Make
250 | .fake/
251 |
252 | # JetBrains Rider
253 | .idea/
254 | *.sln.iml
255 |
256 | # CodeRush
257 | .cr/
258 |
259 | # Python Tools for Visual Studio (PTVS)
260 | __pycache__/
261 | *.pyc
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2018 老九
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # WebApiClient.Extensions
2 | [WebApiClient](https://github.com/dotnetcore/WebApiClient)项目的第三方扩展:[Autofac](https://github.com/autofac/Autofac)、[DependencyInjection](https://github.com/aspnet/DependencyInjection)、[HttpClientFactory](https://github.com/aspnet/HttpClientFactory)、[SteeltoeOSS.Discovery](https://github.com/SteeltoeOSS/Discovery)、[MessagePack](https://github.com/neuecc/MessagePack-CSharp)、[Protobuf](https://github.com/mgravell/protobuf-net)、[Json-Rpc](https://www.jsonrpc.org/specification)
3 |
4 |
5 |
6 | ### 0 Autofac扩展
7 |
8 | #### 0.1 Nuget
9 | PM> `install-package WebApiClient.Extensions.Autofac`
10 |
支持 netstandard1.3
11 |
12 | #### 0.2 使用方法
13 | > 声明远程http服务的的WebApiClient调用接口
14 |
15 | ```c#
16 | [HttpHost("https:/localhost:5000")]
17 | public interface IValuesApi : IHttpApi
18 | {
19 | [HttpGet("api/values")]
20 | ITask GetAsync();
21 |
22 | [HttpGet("api/values/{id}")]
23 | ITask GetAsync(int id);
24 | }
25 | ```
26 | > 注册和配置接口
27 | ```c#
28 | var builder = new ContainerBuilder();
29 | builder.RegisterHttpApi().ConfigureHttpApiConfig(c =>
30 | {
31 | c.HttpHost = new Uri("http://localhost:9999/");
32 | c.FormatOptions.DateTimeFormat = "yyyy-MM-dd HH:mm:ss.fff";
33 | });
34 | ```
35 |
36 | ### 1 DependencyInjection扩展
37 |
38 | #### 1.1 Nuget
39 | PM> `install-package WebApiClient.Extensions.DependencyInjection`
40 |
支持 netstandard2.0
41 |
42 | #### 1.2 使用方法
43 | > 声明远程http服务的的WebApiClient调用接口
44 |
45 | ```c#
46 | [HttpHost("https:/localhost:5000")]
47 | public interface IValuesApi : IHttpApi
48 | {
49 | [HttpGet("api/values")]
50 | ITask GetAsync();
51 |
52 | [HttpGet("api/values/{id}")]
53 | ITask GetAsync(int id);
54 | }
55 | ```
56 |
57 | > Startup相关配置
58 |
59 | ```c#
60 | // This method gets called by the runtime. Use this method to add services to the container.
61 | public void ConfigureServices(IServiceCollection services)
62 | {
63 | services.AddHttpApi().ConfigureHttpApiConfig(c =>
64 | {
65 | c.HttpHost = new Uri("http://localhost:9999/");
66 | c.FormatOptions.DateTimeFormat = "yyyy-MM-dd HH:mm:ss.fff";
67 | });
68 | ...
69 | }
70 | ```
71 |
72 | > Controller
73 |
74 | ```c#
75 | public class HomeController : Controller
76 | {
77 | public async Task Index([FromServices]IValuesApi api, int id = 0)
78 | {
79 | var values = await api.GetValuesAsync();
80 | var value = await api.GetValuesAsync(id);
81 | return "ok";
82 | }
83 | }
84 | ```
85 |
86 | ### 2 HttpClientFactory扩展
87 |
88 | #### 2.1 Nuget
89 | PM> `install-package WebApiClient.Extensions.HttpClientFactory`
90 |
支持 netstandard2.0
91 |
92 | #### 2.2 使用方法
93 | > 声明远程http服务的的WebApiClient调用接口
94 |
95 | ```c#
96 | [HttpHost("https:/localhost:5000")]
97 | public interface IValuesApi : IHttpApi
98 | {
99 | [HttpGet("api/values")]
100 | ITask GetAsync();
101 |
102 | [HttpGet("api/values/{id}")]
103 | ITask GetAsync(int id);
104 | }
105 | ```
106 |
107 | > Startup相关配置
108 |
109 | ```c#
110 | // This method gets called by the runtime. Use this method to add services to the container.
111 | public void ConfigureServices(IServiceCollection services)
112 | {
113 | services.AddHttpApiTypedClient(c =>
114 | {
115 | c.HttpHost = new Uri("http://localhost:9999/");
116 | c.FormatOptions.DateTimeFormat = "yyyy-MM-dd HH:mm:ss.fff";
117 | });
118 | ...
119 | }
120 | ```
121 |
122 | > Controller
123 |
124 | ```c#
125 | public class HomeController : Controller
126 | {
127 | public async Task Index([FromServices]IValuesApi api, int id = 0)
128 | {
129 | var values = await api.GetAsync();
130 | var value = await api.GetAsync(id);
131 | return "ok";
132 | }
133 | }
134 | ```
135 | ### 3 DiscoveryClient扩展
136 |
137 | #### 3.1 Nuget
138 | PM> `install-package WebApiClient.Extensions.DiscoveryClient`
139 |
支持 netstandard2.0
140 |
141 | #### 3.2 使用方法
142 | > 声明微服务的WebApiClient调用接口
143 |
144 | ```c#
145 | [HttpHost("http://VALUES")]
146 | public interface IValuesApi : IHttpApi
147 | {
148 | [HttpGet("api/values")]
149 | ITask GetAsync();
150 |
151 | [HttpGet("api/values/{id}")]
152 | ITask GetAsync(int id);
153 | }
154 | ```
155 |
156 | > Startup相关配置
157 |
158 | ```c#
159 | // This method gets called by the runtime. Use this method to add services to the container.
160 | public void ConfigureServices(IServiceCollection services)
161 | {
162 | services.AddDiscoveryClient(Configuration);
163 | services.AddDiscoveryTypedClient(c =>
164 | {
165 | c.FormatOptions.DateTimeFormat = "yyyy-MM-dd HH:mm:ss.fff";
166 | });
167 | ...
168 | }
169 |
170 |
171 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
172 | public void Configure(IApplicationBuilder app, IHostingEnvironment env)
173 | {
174 | ...
175 | app.UseDiscoveryClient();
176 | }
177 | ```
178 |
179 | > Controller
180 |
181 | ```c#
182 | public class HomeController : Controller
183 | {
184 | public async Task Index([FromServices]IValuesApi api, int id = 0)
185 | {
186 | var values = await api.GetAsync();
187 | var value = await api.GetAsync(id);
188 | return "ok";
189 | }
190 | }
191 | ```
192 |
193 | ### 4 MessagePack扩展
194 |
195 | #### 4.1 Nuget
196 | PM> `install-package WebApiClient.Extensions.MessagePack `
197 |
支持 netstandard1.6 / net4.5
198 |
199 | #### 4.2 使用方法
200 | > 声明远程http服务的的WebApiClient调用接口
201 |
202 | ```c#
203 | [MessagePackReturn]
204 | [HttpHost("https:/localhost:5000")]
205 | public interface IUsersApi : IHttpApi
206 | {
207 | [HttpGet("api/users/{id}")]
208 | ITask GetAsync(int id);
209 |
210 | [HttpPut("api/users")]
211 | ITask PutAsync([MessagePackContent] UserInfo value);
212 | }
213 | ```
214 |
215 | > `asp.net core`服务端MessagePack相关配置
216 |
217 | ```c#
218 | // This method gets called by the runtime. Use this method to add services to the container.
219 | public void ConfigureServices(IServiceCollection services)
220 | {
221 | ...
222 | services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1).AddMvcOptions(o =>
223 | {
224 | o.OutputFormatters.Add(new MessagePackOutputFormatter(ContractlessStandardResolver.Instance));
225 | o.InputFormatters.Add(new MessagePackInputFormatter(ContractlessStandardResolver.Instance));
226 | });
227 | }
228 |
229 |
230 |
231 | class MessagePackInputFormatter : InputFormatter
232 | {
233 | private readonly IFormatterResolver resolver;
234 |
235 | private static readonly StringSegment mediaType = new StringSegment("application/x-msgpack");
236 |
237 | public MessagePackInputFormatter(IFormatterResolver resolver)
238 | {
239 | this.resolver = resolver ?? MessagePackSerializer.DefaultResolver;
240 | this.SupportedMediaTypes.Add(new Microsoft.Net.Http.Headers.MediaTypeHeaderValue(mediaType));
241 | }
242 |
243 | public override Task ReadRequestBodyAsync(InputFormatterContext context)
244 | {
245 | var body = context.HttpContext.Request.Body;
246 | var result = MessagePackSerializer.NonGeneric.Deserialize(context.ModelType, body, resolver);
247 | return InputFormatterResult.SuccessAsync(result);
248 | }
249 | }
250 |
251 | class MessagePackOutputFormatter : OutputFormatter
252 | {
253 | private readonly IFormatterResolver resolver;
254 |
255 | private static readonly StringSegment mediaType = new StringSegment("application/x-msgpack");
256 |
257 | public MessagePackOutputFormatter(IFormatterResolver resolver)
258 | {
259 | this.resolver = resolver ?? MessagePackSerializer.DefaultResolver;
260 | this.SupportedMediaTypes.Add(new Microsoft.Net.Http.Headers.MediaTypeHeaderValue(mediaType));
261 | }
262 |
263 | public override Task WriteResponseBodyAsync(OutputFormatterWriteContext context)
264 | {
265 | if (context.ObjectType != typeof(object))
266 | {
267 | MessagePackSerializer.NonGeneric.Serialize(context.ObjectType, context.HttpContext.Response.Body, context.Object, resolver);
268 | }
269 | else if (context.Object == null)
270 | {
271 | context.HttpContext.Response.Body.WriteByte(MessagePackCode.Nil);
272 | }
273 | else
274 | {
275 | MessagePackSerializer.NonGeneric.Serialize(context.Object.GetType(), context.HttpContext.Response.Body, context.Object, resolver);
276 | }
277 |
278 | context.ContentType = mediaType;
279 | return Task.CompletedTask;
280 | }
281 | }
282 | ```
283 |
284 |
285 | ### 5 Protobuf扩展
286 |
287 | #### 4.1 Nuget
288 | PM> `install-package WebApiClient.Extensions.Protobuf`
289 |
支持 netstandard1.3 / net4.5
290 |
291 | #### 4.2 使用方法
292 | > 声明远程http服务的的WebApiClient调用接口
293 |
294 | ```c#
295 | [ProtobufReturn]
296 | [HttpHost("https:/localhost:5000")]
297 | public interface IUsersApi : IHttpApi
298 | {
299 | [HttpGet("api/users/{id}")]
300 | ITask GetAsync(int id);
301 |
302 | [HttpPut("api/users")]
303 | ITask PutAsync([ProtobufContent] UserInfo value);
304 | }
305 | ```
306 |
307 | > `asp.net core`服务端MessagePack相关配置
308 |
309 | ```c#
310 | // This method gets called by the runtime. Use this method to add services to the container.
311 | public void ConfigureServices(IServiceCollection services)
312 | {
313 | ...
314 | services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1).AddMvcOptions(o =>
315 | {
316 | o.OutputFormatters.Add(new ProtobufOutputFormatter());
317 | o.InputFormatters.Add(new ProtobufInputFormatter());
318 | });
319 | }
320 |
321 |
322 | class ProtobufInputFormatter : InputFormatter
323 | {
324 | private static readonly StringSegment mediaType = new StringSegment("application/x-protobuf");
325 |
326 | public ProtobufInputFormatter()
327 | {
328 | this.SupportedMediaTypes.Add(new Microsoft.Net.Http.Headers.MediaTypeHeaderValue(mediaType));
329 | }
330 |
331 | public override Task ReadRequestBodyAsync(InputFormatterContext context)
332 | {
333 | var body = context.HttpContext.Request.Body;
334 | var model = Serializer.NonGeneric.Deserialize(context.ModelType, body);
335 | return InputFormatterResult.SuccessAsync(model);
336 | }
337 | }
338 |
339 | class ProtobufOutputFormatter : OutputFormatter
340 | {
341 | private static readonly StringSegment mediaType = new StringSegment("application/x-protobuf");
342 |
343 | public ProtobufOutputFormatter()
344 | {
345 | this.SupportedMediaTypes.Add(new Microsoft.Net.Http.Headers.MediaTypeHeaderValue(mediaType));
346 | }
347 |
348 | public override Task WriteResponseBodyAsync(OutputFormatterWriteContext context)
349 | {
350 | var body = context.HttpContext.Response.Body;
351 | Serializer.NonGeneric.Serialize(body, context.Object);
352 | context.ContentType = mediaType;
353 | return Task.CompletedTask;
354 | }
355 | }
356 | ```
357 |
358 | ### 6 Json-Rpc扩展
359 | #### 6.1 Nuget
360 | PM> `install-package WebApiClient.Extensions.JsonRpc`
361 |
支持 netstandard1.3 / net4.5
362 |
363 | #### 4.2 使用方法
364 | > 声明远程Rpc服务的的WebApiClient调用接口
365 |
366 | ```c#
367 | [HttpHost("http://localhost:6800/jsonrpc")]
368 | public interface Aria2 : IHttpApi
369 | {
370 | [JsonRpcMethod("aria2.addUri")]
371 | ITask> AddUriAsync([RpcParam] params string[] uri);
372 | }
373 | ```
374 |
--------------------------------------------------------------------------------
/WebApiClient.Extensions.Autofac/AutofacExtensions.cs:
--------------------------------------------------------------------------------
1 |
2 | using Autofac;
3 |
4 | namespace WebApiClient.Extensions.Autofac
5 | {
6 | ///
7 | /// 基于Autofac的扩展
8 | ///
9 | public static class AutofacExtensions
10 | {
11 | ///
12 | /// 注册HttpApi
13 | /// 返回HttpApi工厂创建器
14 | ///
15 | /// 接口类型
16 | ///
17 | ///
18 | public static HttpApiFactoryBuilder RegisterHttpApi(this ContainerBuilder builder)
19 | where TInterface : class, IHttpApi
20 | {
21 | return new HttpApiFactoryBuilder(builder);
22 | }
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/WebApiClient.Extensions.Autofac/AutofacServiceProvider.cs:
--------------------------------------------------------------------------------
1 | using Autofac;
2 | using System;
3 |
4 | namespace WebApiClient.Extensions.Autofac
5 | {
6 | ///
7 | /// 表示Autofac实现的ServiceProvider
8 | ///
9 | class AutofacServiceProvider : IServiceProvider
10 | {
11 | ///
12 | /// 组件上下文
13 | ///
14 | private readonly IComponentContext context;
15 |
16 | ///
17 | /// Autofac实现的ServiceProvider
18 | ///
19 | /// 组件上下文
20 | public AutofacServiceProvider(IComponentContext context)
21 | {
22 | this.context = context.Resolve();
23 | }
24 |
25 | ///
26 | /// 获取服务
27 | ///
28 | ///
29 | ///
30 | public T GetService()
31 | {
32 | return (T)this.GetService(typeof(T));
33 | }
34 |
35 | ///
36 | /// 获取服务
37 | ///
38 | /// 服务类型
39 | ///
40 | public object GetService(Type serviceType)
41 | {
42 | return this.context.ResolveOptional(serviceType);
43 | }
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/WebApiClient.Extensions.Autofac/HttpApiFactoryBuilder.cs:
--------------------------------------------------------------------------------
1 | using Autofac;
2 | using System;
3 | using System.Net.Http;
4 |
5 | namespace WebApiClient.Extensions.Autofac
6 | {
7 | ///
8 | /// HttpApi实例工厂创建器
9 | ///
10 | ///
11 | public class HttpApiFactoryBuilder where TInterface : class, IHttpApi
12 | {
13 | private bool keepCookieContainer = true;
14 |
15 | private TimeSpan lifeTime = TimeSpan.FromMinutes(2d);
16 |
17 | private TimeSpan cleanupInterval = TimeSpan.FromSeconds(10d);
18 |
19 | private Action configOptions;
20 |
21 | private Func handlerFactory;
22 |
23 |
24 | ///
25 | /// HttpApi实例工厂创建器
26 | ///
27 | ///
28 | public HttpApiFactoryBuilder(ContainerBuilder builder)
29 | {
30 | builder.Register(ctx =>
31 | {
32 | var provider = new AutofacServiceProvider(ctx);
33 | return new HttpApiFactory()
34 | .SetLifetime(this.lifeTime)
35 | .SetCleanupInterval(this.cleanupInterval)
36 | .SetKeepCookieContainer(this.keepCookieContainer)
37 | .ConfigureHttpMessageHandler(() => this.handlerFactory?.Invoke(provider));
38 | })
39 | .As>()
40 | .SingleInstance();
41 |
42 | builder.Register(ctx =>
43 | {
44 | var provider = new AutofacServiceProvider(ctx);
45 | var factory = provider.GetService>();
46 | factory.ConfigureHttpApiConfig(c =>
47 | {
48 | c.ServiceProvider = provider;
49 | this.configOptions?.Invoke(c, provider);
50 | });
51 | return factory.CreateHttpApi();
52 | })
53 | .As()
54 | .InstancePerDependency();
55 | }
56 |
57 | ///
58 | /// 配置HttpApiConfig
59 | ///
60 | /// 配置选项
61 | ///
62 | ///
63 | public HttpApiFactoryBuilder ConfigureHttpApiConfig(Action configOptions)
64 | {
65 | if (configOptions == null)
66 | {
67 | throw new ArgumentNullException(nameof(configOptions));
68 | }
69 | return this.ConfigureHttpApiConfig((c, p) => configOptions.Invoke(c));
70 | }
71 |
72 |
73 | ///
74 | /// 配置HttpApiConfig
75 | ///
76 | /// 配置选项
77 | ///
78 | ///
79 | public HttpApiFactoryBuilder ConfigureHttpApiConfig(Action configOptions)
80 | {
81 | this.configOptions = configOptions ?? throw new ArgumentNullException(nameof(configOptions));
82 | return this;
83 | }
84 |
85 | ///
86 | /// 配置HttpMessageHandler的创建
87 | ///
88 | /// 创建委托
89 | ///
90 | ///
91 | public HttpApiFactoryBuilder ConfigureHttpMessageHandler(Func handlerFactory)
92 | {
93 | if (handlerFactory == null)
94 | {
95 | throw new ArgumentNullException(nameof(handlerFactory));
96 | }
97 | return this.ConfigureHttpMessageHandler(p => handlerFactory.Invoke());
98 | }
99 |
100 | ///
101 | /// 配置HttpMessageHandler的创建
102 | ///
103 | /// 创建委托
104 | ///
105 | ///
106 | public HttpApiFactoryBuilder ConfigureHttpMessageHandler(Func handlerFactory)
107 | {
108 | this.handlerFactory = handlerFactory ?? throw new ArgumentNullException(nameof(handlerFactory));
109 | return this;
110 | }
111 |
112 | ///
113 | /// 置HttpApi实例的生命周期
114 | ///
115 | /// 生命周期
116 | ///
117 | ///
118 | public HttpApiFactoryBuilder SetLifetime(TimeSpan lifeTime)
119 | {
120 | if (lifeTime <= TimeSpan.Zero)
121 | {
122 | throw new ArgumentOutOfRangeException(nameof(lifeTime));
123 | }
124 | this.lifeTime = lifeTime;
125 | return this;
126 | }
127 |
128 |
129 | ///
130 | /// 获取或设置清理过期的HttpApi实例的时间间隔
131 | ///
132 | /// 时间间隔
133 | ///
134 | ///
135 | public HttpApiFactoryBuilder SetCleanupInterval(TimeSpan interval)
136 | {
137 | if (interval <= TimeSpan.Zero)
138 | {
139 | throw new ArgumentOutOfRangeException(nameof(interval));
140 | }
141 | this.cleanupInterval = interval;
142 | return this;
143 | }
144 |
145 | ///
146 | /// 设置是否维护使用一个CookieContainer实例 该实例为首次创建时的CookieContainer
147 | ///
148 | /// true维护使用一个CookieContainer实例
149 | ///
150 | public HttpApiFactoryBuilder SetKeepCookieContainer(bool keep)
151 | {
152 | this.keepCookieContainer = keep;
153 | return this;
154 | }
155 | }
156 | }
157 |
--------------------------------------------------------------------------------
/WebApiClient.Extensions.Autofac/WebApiClient.Extensions.Autofac.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netstandard1.3
5 | true
6 | 2.0.3
7 | Copyright © xljiulang 2019
8 | WebApiClient.JIT的Autofac扩展
9 | WebApiClient.JIT的Autofac扩展
10 | xljiulang
11 | https://github.com/xljiulang/WebApiClient.Extensions
12 | https://raw.githubusercontent.com/dotnetcore/WebApiClient/master/icon.png
13 | bin\$(Configuration)\$(TargetFramework)\$(AssemblyName).xml
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/WebApiClient.Extensions.DependencyInjection/DependencyInjectionExtensions.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.Extensions.DependencyInjection;
2 |
3 | namespace WebApiClient.Extensions.DependencyInjection
4 | {
5 | ///
6 | /// 基于DependencyInjection的扩展
7 | ///
8 | public static class DependencyInjectionExtensions
9 | {
10 | ///
11 | /// 添加HttpApi
12 | /// 返回HttpApi工厂
13 | ///
14 | /// 接口类型
15 | ///
16 | ///
17 | public static HttpApiFactoryBuilder AddHttpApi(this IServiceCollection services)
18 | where TInterface : class, IHttpApi
19 | {
20 | return new HttpApiFactoryBuilder(services);
21 | }
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/WebApiClient.Extensions.DependencyInjection/HttpApiFactoryBuilder.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.Extensions.DependencyInjection;
2 | using System;
3 | using System.Net.Http;
4 |
5 | namespace WebApiClient.Extensions.DependencyInjection
6 | {
7 | ///
8 | /// HttpApi实例工厂创建器
9 | ///
10 | ///
11 | public class HttpApiFactoryBuilder where TInterface : class, IHttpApi
12 | {
13 | private bool keepCookieContainer = true;
14 |
15 | private TimeSpan lifeTime = TimeSpan.FromMinutes(2d);
16 |
17 | private TimeSpan cleanupInterval = TimeSpan.FromSeconds(10d);
18 |
19 | private Action configOptions;
20 |
21 | private Func handlerFactory;
22 |
23 |
24 | ///
25 | /// HttpApi实例工厂创建器
26 | ///
27 | ///
28 | public HttpApiFactoryBuilder(IServiceCollection services)
29 | {
30 | services.AddSingleton, HttpApiFactory>(p =>
31 | {
32 | return new HttpApiFactory()
33 | .SetLifetime(this.lifeTime)
34 | .SetCleanupInterval(this.cleanupInterval)
35 | .SetKeepCookieContainer(this.keepCookieContainer)
36 | .ConfigureHttpMessageHandler(() => this.handlerFactory?.Invoke(p));
37 | });
38 |
39 | services.AddTransient(p =>
40 | {
41 | var factory = p.GetRequiredService>();
42 | factory.ConfigureHttpApiConfig(c =>
43 | {
44 | c.ServiceProvider = p;
45 | this.configOptions?.Invoke(c, p);
46 | });
47 | return factory.CreateHttpApi();
48 | });
49 | }
50 |
51 | ///
52 | /// 配置HttpApiConfig
53 | ///
54 | /// 配置选项
55 | ///
56 | ///
57 | public HttpApiFactoryBuilder ConfigureHttpApiConfig(Action configOptions)
58 | {
59 | if (configOptions == null)
60 | {
61 | throw new ArgumentNullException(nameof(configOptions));
62 | }
63 | return this.ConfigureHttpApiConfig((c, p) => configOptions.Invoke(c));
64 | }
65 |
66 |
67 | ///
68 | /// 配置HttpApiConfig
69 | ///
70 | /// 配置选项
71 | ///
72 | ///
73 | public HttpApiFactoryBuilder ConfigureHttpApiConfig(Action configOptions)
74 | {
75 | this.configOptions = configOptions ?? throw new ArgumentNullException(nameof(configOptions));
76 | return this;
77 | }
78 |
79 | ///
80 | /// 配置HttpMessageHandler的创建
81 | ///
82 | /// 创建委托
83 | ///
84 | ///
85 | public HttpApiFactoryBuilder ConfigureHttpMessageHandler(Func handlerFactory)
86 | {
87 | if (handlerFactory == null)
88 | {
89 | throw new ArgumentNullException(nameof(handlerFactory));
90 | }
91 | return this.ConfigureHttpMessageHandler(p => handlerFactory.Invoke());
92 | }
93 |
94 | ///
95 | /// 配置HttpMessageHandler的创建
96 | ///
97 | /// 创建委托
98 | ///
99 | ///
100 | public HttpApiFactoryBuilder ConfigureHttpMessageHandler(Func handlerFactory)
101 | {
102 | this.handlerFactory = handlerFactory ?? throw new ArgumentNullException(nameof(handlerFactory));
103 | return this;
104 | }
105 |
106 | ///
107 | /// 置HttpApi实例的生命周期
108 | ///
109 | /// 生命周期
110 | ///
111 | ///
112 | public HttpApiFactoryBuilder SetLifetime(TimeSpan lifeTime)
113 | {
114 | if (lifeTime <= TimeSpan.Zero)
115 | {
116 | throw new ArgumentOutOfRangeException(nameof(lifeTime));
117 | }
118 | this.lifeTime = lifeTime;
119 | return this;
120 | }
121 |
122 |
123 | ///
124 | /// 获取或设置清理过期的HttpApi实例的时间间隔
125 | ///
126 | /// 时间间隔
127 | ///
128 | ///
129 | public HttpApiFactoryBuilder SetCleanupInterval(TimeSpan interval)
130 | {
131 | if (interval <= TimeSpan.Zero)
132 | {
133 | throw new ArgumentOutOfRangeException(nameof(interval));
134 | }
135 | this.cleanupInterval = interval;
136 | return this;
137 | }
138 |
139 | ///
140 | /// 设置是否维护使用一个CookieContainer实例 该实例为首次创建时的CookieContainer
141 | ///
142 | /// true维护使用一个CookieContainer实例
143 | ///
144 | public HttpApiFactoryBuilder SetKeepCookieContainer(bool keep)
145 | {
146 | this.keepCookieContainer = keep;
147 | return this;
148 | }
149 | }
150 | }
151 |
--------------------------------------------------------------------------------
/WebApiClient.Extensions.DependencyInjection/WebApiClient.Extensions.DependencyInjection.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netstandard2.0
5 | true
6 | 2.0.3
7 | Copyright © xljiulang 2018
8 | WebApiClient.JIT的DependencyInjection扩展
9 | WebApiClient.JIT的DependencyInjection扩展
10 | xljiulang
11 | https://github.com/xljiulang/WebApiClient.Extensions
12 | https://raw.githubusercontent.com/dotnetcore/WebApiClient/master/icon.png
13 | bin\$(Configuration)\$(TargetFramework)\$(AssemblyName).xml
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/WebApiClient.Extensions.DiscoveryClient/DiscoveryClientExtensions.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.Extensions.DependencyInjection;
2 | using Steeltoe.Common.Discovery;
3 | using System;
4 | using WebApiClient.Extensions.HttpClientFactory;
5 |
6 | namespace WebApiClient.Extensions.DiscoveryClient
7 | {
8 | ///
9 | /// 基于HttpClientFactory的DiscoveryClient扩展
10 | ///
11 | public static class DiscoveryClientExtensions
12 | {
13 | ///
14 | /// 添加Discovery的别名HttpClient
15 | ///
16 | /// 接口类型
17 | ///
18 | ///
19 | public static IHttpClientBuilder AddDiscoveryTypedClient(this IServiceCollection services)
20 | where TInterface : class, IHttpApi
21 | {
22 | return services.AddDiscoveryTypedClient(c => { });
23 | }
24 |
25 | ///
26 | /// 添加Discovery的别名HttpClient
27 | ///
28 | /// 接口类型
29 | ///
30 | /// 配置选项
31 | ///
32 | ///
33 | public static IHttpClientBuilder AddDiscoveryTypedClient(this IServiceCollection services, Action configOptions)
34 | where TInterface : class, IHttpApi
35 | {
36 | if (configOptions == null)
37 | {
38 | throw new ArgumentNullException(nameof(configOptions));
39 | }
40 |
41 | return services.AddDiscoveryTypedClient((c, p) => configOptions.Invoke(c));
42 | }
43 |
44 | ///
45 | /// 添加Discovery的别名HttpClient
46 | ///
47 | /// 接口类型
48 | ///
49 | /// 配置选项
50 | ///
51 | ///
52 | public static IHttpClientBuilder AddDiscoveryTypedClient(this IServiceCollection services, Action configOptions)
53 | where TInterface : class, IHttpApi
54 | {
55 | if (configOptions == null)
56 | {
57 | throw new ArgumentNullException(nameof(configOptions));
58 | }
59 |
60 | return services
61 | .AddHttpApiTypedClient(configOptions)
62 | .ConfigurePrimaryHttpMessageHandler(provider =>
63 | {
64 | var discoveryClient = provider.GetService();
65 | return new DiscoveryHttpClientHandler(discoveryClient);
66 | });
67 | }
68 | }
69 | }
70 |
--------------------------------------------------------------------------------
/WebApiClient.Extensions.DiscoveryClient/WebApiClient.Extensions.DiscoveryClient.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netstandard2.0
5 | true
6 | 2.0.3
7 | WebApiClient.JIT的DiscoveryClient扩展
8 | WebApiClient.JIT的DiscoveryClient扩展
9 | Copyright © xljiulang 2018
10 | https://github.com/xljiulang/WebApiClient.Extensions
11 | https://raw.githubusercontent.com/dotnetcore/WebApiClient/master/icon.png
12 | xljiulang
13 | bin\$(Configuration)\$(TargetFramework)\$(AssemblyName).xml
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/WebApiClient.Extensions.HttpClientFactory/HttpClientFactoryExtensions.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.Extensions.DependencyInjection;
2 | using System;
3 |
4 | namespace WebApiClient.Extensions.HttpClientFactory
5 | {
6 | ///
7 | /// 基于HttpClientFactory的扩展
8 | ///
9 | public static class HttpClientFactoryExtensions
10 | {
11 | ///
12 | /// 添加HttpApiClient的别名HttpClient
13 | ///
14 | /// 接口类型
15 | ///
16 | ///
17 | public static IHttpClientBuilder AddHttpApiTypedClient(this IServiceCollection services)
18 | where TInterface : class, IHttpApi
19 | {
20 | return services.AddHttpApiTypedClient(c => { });
21 | }
22 |
23 | ///
24 | /// 添加HttpApiClient的别名HttpClient
25 | ///
26 | /// 接口类型
27 | ///
28 | /// 配置选项
29 | ///
30 | ///
31 | public static IHttpClientBuilder AddHttpApiTypedClient(this IServiceCollection services, Action configOptions)
32 | where TInterface : class, IHttpApi
33 | {
34 | if (configOptions == null)
35 | {
36 | throw new ArgumentNullException(nameof(configOptions));
37 | }
38 |
39 | return services.AddHttpApiTypedClient((c, p) => configOptions.Invoke(c));
40 | }
41 |
42 | ///
43 | /// 添加HttpApiClient的别名HttpClient
44 | ///
45 | /// 接口类型
46 | ///
47 | /// 配置选项
48 | ///
49 | ///
50 | public static IHttpClientBuilder AddHttpApiTypedClient(this IServiceCollection services, Action configOptions)
51 | where TInterface : class, IHttpApi
52 | {
53 | if (configOptions == null)
54 | {
55 | throw new ArgumentNullException(nameof(configOptions));
56 | }
57 |
58 | return services
59 | .AddHttpClient(typeof(TInterface).ToString())
60 | .AddTypedClient((httpClient, provider) =>
61 | {
62 | var httpApiConfig = new HttpApiConfig(httpClient)
63 | {
64 | ServiceProvider = provider
65 | };
66 | configOptions.Invoke(httpApiConfig, provider);
67 | return HttpApi.Create(httpApiConfig);
68 | });
69 | }
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/WebApiClient.Extensions.HttpClientFactory/WebApiClient.Extensions.HttpClientFactory.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netstandard2.0
5 | true
6 | 2.1.0
7 | Copyright © xljiulang 2018
8 | WebApiClient.JIT的HttpClientFactory扩展
9 | WebApiClient.JIT的HttpClientFactory扩展
10 | xljiulang
11 | https://github.com/xljiulang/WebApiClient.Extensions
12 | https://raw.githubusercontent.com/dotnetcore/WebApiClient/master/icon.png
13 | bin\$(Configuration)\$(TargetFramework)\$(AssemblyName).xml
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/WebApiClient.Extensions.JsonRpc/JsonRpc.cs:
--------------------------------------------------------------------------------
1 | using System.Threading;
2 | using System.Threading.Tasks;
3 |
4 | namespace WebApiClient
5 | {
6 | ///
7 | /// 提供JsonRpc的一些常量
8 | ///
9 | static class JsonRpc
10 | {
11 | ///
12 | /// id值
13 | ///
14 | private static int @id = 0;
15 |
16 | ///
17 | /// 内容类型描述
18 | ///
19 | public static readonly string ContentType = "application/json-rpc";
20 |
21 | #if NET45
22 | ///
23 | /// 表示已完成的任务
24 | ///
25 | public static readonly Task CompletedTask = Task.FromResult