CARVIEW |
Select Language
HTTP/2 200
date: Wed, 23 Jul 2025 00:48:10 GMT
content-type: text/html; charset=utf-8
vary: X-PJAX, X-PJAX-Container, Turbo-Visit, Turbo-Frame, X-Requested-With,Accept-Encoding, Accept, X-Requested-With
etag: W/"845fbc825c3fcbeac1571cc2e1fca68a"
cache-control: max-age=0, private, must-revalidate
strict-transport-security: max-age=31536000; includeSubdomains; preload
x-frame-options: deny
x-content-type-options: nosniff
x-xss-protection: 0
referrer-policy: no-referrer-when-downgrade
content-security-policy: default-src 'none'; base-uri 'self'; child-src github.githubassets.com github.com/assets-cdn/worker/ github.com/assets/ gist.github.com/assets-cdn/worker/; connect-src 'self' uploads.github.com www.githubstatus.com collector.github.com raw.githubusercontent.com api.github.com github-cloud.s3.amazonaws.com github-production-repository-file-5c1aeb.s3.amazonaws.com github-production-upload-manifest-file-7fdce7.s3.amazonaws.com github-production-user-asset-6210df.s3.amazonaws.com *.rel.tunnels.api.visualstudio.com wss://*.rel.tunnels.api.visualstudio.com objects-origin.githubusercontent.com copilot-proxy.githubusercontent.com proxy.individual.githubcopilot.com proxy.business.githubcopilot.com proxy.enterprise.githubcopilot.com *.actions.githubusercontent.com wss://*.actions.githubusercontent.com productionresultssa0.blob.core.windows.net/ productionresultssa1.blob.core.windows.net/ productionresultssa2.blob.core.windows.net/ productionresultssa3.blob.core.windows.net/ productionresultssa4.blob.core.windows.net/ productionresultssa5.blob.core.windows.net/ productionresultssa6.blob.core.windows.net/ productionresultssa7.blob.core.windows.net/ productionresultssa8.blob.core.windows.net/ productionresultssa9.blob.core.windows.net/ productionresultssa10.blob.core.windows.net/ productionresultssa11.blob.core.windows.net/ productionresultssa12.blob.core.windows.net/ productionresultssa13.blob.core.windows.net/ productionresultssa14.blob.core.windows.net/ productionresultssa15.blob.core.windows.net/ productionresultssa16.blob.core.windows.net/ productionresultssa17.blob.core.windows.net/ productionresultssa18.blob.core.windows.net/ productionresultssa19.blob.core.windows.net/ github-production-repository-image-32fea6.s3.amazonaws.com github-production-release-asset-2e65be.s3.amazonaws.com insights.github.com wss://alive.github.com api.githubcopilot.com api.individual.githubcopilot.com api.business.githubcopilot.com api.enterprise.githubcopilot.com; font-src github.githubassets.com; form-action 'self' github.com gist.github.com copilot-workspace.githubnext.com objects-origin.githubusercontent.com; frame-ancestors 'none'; frame-src viewscreen.githubusercontent.com notebooks.githubusercontent.com; img-src 'self' data: blob: github.githubassets.com media.githubusercontent.com camo.githubusercontent.com identicons.github.com avatars.githubusercontent.com private-avatars.githubusercontent.com github-cloud.s3.amazonaws.com objects.githubusercontent.com release-assets.githubusercontent.com secured-user-images.githubusercontent.com/ user-images.githubusercontent.com/ private-user-images.githubusercontent.com opengraph.githubassets.com copilotprodattachments.blob.core.windows.net/github-production-copilot-attachments/ github-production-user-asset-6210df.s3.amazonaws.com customer-stories-feed.github.com spotlights-feed.github.com objects-origin.githubusercontent.com *.githubusercontent.com; manifest-src 'self'; media-src github.com user-images.githubusercontent.com/ secured-user-images.githubusercontent.com/ private-user-images.githubusercontent.com github-production-user-asset-6210df.s3.amazonaws.com gist.github.com; script-src github.githubassets.com; style-src 'unsafe-inline' github.githubassets.com; upgrade-insecure-requests; worker-src github.githubassets.com github.com/assets-cdn/worker/ github.com/assets/ gist.github.com/assets-cdn/worker/
server: github.com
content-encoding: gzip
accept-ranges: bytes
set-cookie: _gh_sess=rp6gbbTMgB3mCDov1FUrfE062l%2FuBUFDgb5KDrXoOkausSGWBwa6TRMS5om13%2BsN1PO9J11tW02oK9vXJsZ4p12nHx3O2Amk8L85WQx77H6htHqOnpPbdhHHYaMubYlZW3WWywCdXLgxaIefN%2BoMNcHDqeEGZPKRrYYO2zdBFFTnyb4YCmKVkecGvABVsGlqR%2F3TJ3eMn%2BBlwNf6PwXokFNZS8JhACGDp2rhptQhxKPhiTnAjx%2BcmNSt0vCoX79kb41v6L1gHfekHfy8Aa%2FVbg%3D%3D--ogBqY32QOiHs%2BY1B--xVv5wvdgW2Iq4hUBKLX96A%3D%3D; Path=/; HttpOnly; Secure; SameSite=Lax
set-cookie: _octo=GH1.1.138658274.1753231690; Path=/; Domain=github.com; Expires=Thu, 23 Jul 2026 00:48:10 GMT; Secure; SameSite=Lax
set-cookie: logged_in=no; Path=/; Domain=github.com; Expires=Thu, 23 Jul 2026 00:48:10 GMT; HttpOnly; Secure; SameSite=Lax
x-github-request-id: E4F2:12BD61:206FC6:2D79AA:6880314A
WebApiClient进阶 · dotnetcore/WebApiClient Wiki · GitHub
Skip to content
Navigation Menu
{{ message }}
-
Notifications
You must be signed in to change notification settings - Fork 447
WebApiClient进阶
老九 edited this page Mar 25, 2020
·
13 revisions
本章节将向读者讲解如何在不同的项目环境下,选择适合的方式来创建http声明接口的代理类。
接口声明
public interface IMyWebApi : IHttpApi
{
[HttpGet("user/{id}")]
ITask<UserInfo> GetUserAsync(string id);
}
初始化代码(只能调用一次)
HttpApi.Register<IMyWebApi>().ConfigureHttpApiConfig(c =>
{
// 可以替换的序列化工具
c.JsonFormatter = null;
c.XmlFormatter = null;
c.KeyValueFormatter = null;
// 参数验证和返回值验证,使用System.ComponentModel.DataAnnotations验证特性
c.UseParameterPropertyValidate = false;
c.UseReturnValuePropertyValidate = false;
// 请求主机和HttpClient相关配置
c.HttpHost = new Uri("https://localhost:9999/");
c.HttpClient.Timeout = TimeSpan.FromMinutes(2d);
// 格式相关配置
c.FormatOptions.UseCamelCase = true;
c.FormatOptions.DateTimeFormat = DateTimeFormats.ISO8601_WithMillisecond;
// 响应缓存提供者配置,配合[CacheAttribute]来使用
c.ResponseCacheProvider = null;
// 服务提供者,实例一般由DI创建得到
// 对于Asp.net core,此ServiceProvider应该为请求时创建的ServiceProvider,而不是ConfigureServices()创建的根ServiceProvider
c.ServiceProvider = null;
// 日志工厂,可以自主创建并赋值,如果保留为null,获取其实例时则从ServiceProvider获取
c.LoggerFactory = null;
});
调用http请求代码
var myWebApi = HttpApi.Resolve<IMyWebApi>();
var user = await myWebApi.GetUserAsync("id001");
使用Register/Resolve的好处是在入口处只Register一次IMyWebApi,由HttpApiFactory自动接理IMyWebApi的生命周期管理。在使用中,不用处理myWebApi实例的释放(手动Dispose也不会释放),在一定的时间内都是获取到同一个myWebApi实例,当实例生命超过配置的周期时,自动被跟踪释放,并提供返回下一个一样配置的myWebApi实例。
接口声明
public interface IMyWebApi : IHttpApi
{
[HttpGet("user/{id}")]
ITask<UserInfo> GetUserAsync(string id);
}
Startup.cs配置依赖注入
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpApi<IMyWebApi>();
services.ConfigureHttpApi<IMyWebApi>(o=>
{
o.HttpHost = new Uri("https://localhost:9999/");
...
});
}
Controller代码
public class HomeController : Controller
{
public async Task<UserInfo> Index([FromServices]IMyWebApi myWebApi)
{
return await myWebApi.GetUserAsync("id001");
}
}
接口声明
public interface IMyWebApi : IHttpApi
{
[HttpGet("user/{id}")]
ITask<UserInfo> GetUserAsync(string id);
}
Global.asax.cs Application_Start
var builder = new ContainerBuilder();
builder.RegisterControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired();
builder.Register(_ => new HttpApiFactory<IMyWebApi>()
.ConfigureHttpApiConfig(c =>
{
c.HttpHost = new Uri("https://localhost:9999/");
c.FormatOptions.DateTimeFormat = DateTimeFormats.ISO8601_WithMillisecond;
}))
.As<IHttpApiFactory<IMyWebApi>>()
.SingleInstance();
builder.Register(c => c.Resolve<IHttpApiFactory<IMyWebApi>>().CreateHttpApi())
.As<IMyWebApi>()
.InstancePerHttpRequest();
DependencyResolver.SetResolver(new AutofacDependencyResolver(builder.Build()));
Controller
public class HomeController : Controller
{
public IMyWebApi MyWebApi { get; set; }
public async Task<ActionResult> Index()
{
var user = await this.MyWebApi.GetUserAsync("id001");
return View(user);
}
}
Clone this wiki locally
You can’t perform that action at this time.