HttpClientFactory封装,如有错误请指出,谢谢!

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks; namespace Hx.HttpClientFactory
{
public class HxHttpClient:IHxHttpClient
{
private readonly IHttpClientFactory _clientFactory;
public HxHttpClient(IHttpClientFactory clientFactory)
{
_clientFactory = clientFactory;
}
public Task<HttpResponseMessage> SendAsync(string url, string data, string contentType = "text/json")
{
var request = new HttpRequestMessage(HttpMethod.Post,
new Uri(url));
request.Headers.Clear();
request.Content = new StringContent(data);
//request.Headers.Remove("Content-Type");
request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);//("text/json");
var client = _clientFactory.CreateClient();
return client.SendAsync(request);
}
}
}
using System;
using System.Collections.Generic;
using System.Text; namespace Hx.HttpClientFactory
{
public class HxHttpClientFactory : HxHttpClientFactoryBase<IHxHttpClient, HxHttpClient>, IHxHttpClientFactory
{
}
}
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Text; namespace Hx.HttpClientFactory
{
public class HxHttpClientFactoryBase<IT, T> : IHxHttpClientFactory<IT, T> where T : class, IT
where IT : class
{
private IHost _host;
public HxHttpClientFactoryBase()
{
var builder = new HostBuilder()
.ConfigureServices((hostContext, services) =>
{
services.AddHttpClient();
services.AddTransient<IT, T>();
}).UseConsoleLifetime();
_host = builder.Build();
}
public IT CreateHttpClient()
{
using (var serviceScope = _host.Services.CreateScope())
{
var service = serviceScope.ServiceProvider;
return service.GetRequiredService<IT>();
}
}
}
}
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks; namespace Hx.HttpClientFactory
{
public interface IHxHttpClient
{
Task<HttpResponseMessage> SendAsync(string url, string data, string contentType = "text/json");
}
}
using System;
using System.Collections.Generic;
using System.Text; namespace Hx.HttpClientFactory
{
public interface IHxHttpClientFactory<IT,T> where T : class, IT
where IT : class
{
IT CreateHttpClient();
}
public interface IHxHttpClientFactory : IHxHttpClientFactory<IHxHttpClient, HxHttpClient>
{ }
}
using System;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using SampleApp; class Program
{
static async Task<int> Main(string[] args)
{
IHxHttpClientFactory factory = new HxHttpClientFactory();
var client= factory.CreateHttpClient();
var t= await client.SendAsync("url", "body字符串"); if (t.IsSuccessStatusCode)
{ }


*注意:本示例类不是静态的如果没有使用注入使用时请考虑静态类
05-11 20:23