main
wanggaofeng
parent 5299d817db
commit 4a0b275560

@ -1,6 +1,6 @@
namespace HttpClientStudy.Config namespace HttpClientStudy.Config
{ {
public class WebApiOption public class WebApiConfig
{ {
public string BaseUrl { get; set; } public string BaseUrl { get; set; }
} }

@ -45,7 +45,7 @@ namespace HttpClientStudy.Config
services.AddOptions(); services.AddOptions();
var configuration = services.BuildServiceProvider().GetService<IConfiguration>(); var configuration = services.BuildServiceProvider().GetService<IConfiguration>();
services.Configure<WebApiOption>(configuration.GetSection("WebApi")); services.Configure<WebApiConfig>(configuration.GetSection("WebApi"));
return services; return services;
} }

@ -0,0 +1,39 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
namespace HttpClientStudy.Config
{
public static class WebApiConfigManager
{
public static WebApiConfig GetWebApiConfig()
{
return GetWebApiConfigOption().CurrentValue;
}
public static IOptionsMonitor<WebApiConfig> GetWebApiConfigOption()
{
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
configurationBuilder.AddWebApiConfigration();
ServiceCollection services = new ServiceCollection();
services.AddSingleton<IConfiguration>(configurationBuilder.Build());
services.AddWebApiOptions();
var webApiConfigOption = services.BuildServiceProvider().GetService<IOptionsMonitor<WebApiConfig>>();
if (webApiConfigOption == null)
{
throw new OptionsValidationException(nameof(webApiConfigOption), typeof(IOptions<WebApiConfig>), new[] { "获取配置异常"});
}
return webApiConfigOption;
}
}
}

@ -1,33 +1,70 @@
namespace HttpClientStudy.Core using HttpClientStudy.Config;
using Microsoft.Extensions.Options;
namespace HttpClientStudy.Core
{ {
/// <summary> /// <summary>
/// Http 错误处理 /// Http 错误处理
/// <list type="number">
/// <listheader>
/// <term>常见方式</term>
/// <description>(仅个人见解)</description>
/// </listheader>
/// <item>
/// <term>HtppClient 提供的状态码、EnsureSuccessStatusCode()等机制</term>
/// <description>(适用HttpClient内部错误)</description>
/// </item>
/// <item>
/// <term>Try Catch 方式</term>
/// <description>(适用外部)</description>
/// </item>
/// <item>
/// <term>使用 Polly 类库</term>
/// <description>(更多功能)</description>
/// </item>
/// </list>
/// </summary> /// </summary>
/// <remarks>
/// 简化处理
/// </remarks>
public class HttpError public class HttpError
{ {
// 定义一个 HttpClient 实例,共享 // 定义一个 HttpClient 实例,共享
public static HttpClient HttpClient = new HttpClient(new SocketsHttpHandler() { PooledConnectionLifetime = TimeSpan.FromMinutes(1) }) public static HttpClient HttpClient = new HttpClient(new SocketsHttpHandler() { PooledConnectionLifetime = TimeSpan.FromMinutes(1) })
{ {
BaseAddress = new Uri(WebApiConfig.WebApiBaseUrl) BaseAddress = new Uri(WebApiConfigManager.GetWebApiConfig().BaseUrl)
}; };
public async Task<HttpStatusCode> UrlNotFoundAsync() /// <summary>
/// 未知主机错误
/// </summary>
/// <returns></returns>
public async Task<HttpStatusCode> UnknownHostAsync()
{ {
var response = await HttpClient.GetAsync("http://www.notingxxxxxxxx.com/404.html"); var response = await HttpClient.GetAsync("http://www.unknowhost_nonono.com/404.html");
response.EnsureSuccessStatusCode();
return response.StatusCode; return response.StatusCode;
} }
/// <summary>
/// 404错误
/// </summary>
/// <returns></returns>
public async Task<HttpStatusCode> Http404Async() public async Task<HttpStatusCode> Http404Async()
{ {
var response = await HttpClient.GetAsync("http://www.baidu.com/404.html"); var response = await HttpClient.GetAsync("/404.html");
response.EnsureSuccessStatusCode();
return response.StatusCode; return response.StatusCode;
} }
/// <summary>
/// 服务器错误
/// </summary>
/// <returns></returns>
public async Task<HttpStatusCode> Http500Async()
{
var response = await HttpClient.GetAsync("/api/ErrorDemo/Error500");
return response.StatusCode;
}
} }
} }

@ -1,7 +0,0 @@
namespace HttpClientStudy.Core
{
public class WebApiConfig
{
public const string WebApiBaseUrl = "http://localhost:5189";
}
}

@ -8,7 +8,6 @@
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\HttpClientStudy.Core\HttpClientStudy.Core.csproj" /> <ProjectReference Include="..\HttpClientStudy.Core\HttpClientStudy.Core.csproj" />
<ProjectReference Include="..\HttpClientStudy.Model\HttpClientStudy.Model.csproj" />
</ItemGroup> </ItemGroup>
</Project> </Project>

@ -28,13 +28,24 @@ namespace HttpClientStudy.UnitTest.ConfigTest
services.AddWebApiOptions(); services.AddWebApiOptions();
var provider = services.BuildServiceProvider(); var provider = services.BuildServiceProvider();
IOptions<WebApiOption> webApiOptions = provider.GetService<IOptions<WebApiOption>>(); IOptions<Config.WebApiConfig> webApiOptions = provider.GetService<IOptions<Config.WebApiConfig>>();
var webApiConfig = webApiOptions.Value; var webApiConfig = webApiOptions.Value;
Assert.NotNull(webApiOptions); Assert.NotNull(webApiOptions);
Assert.NotEmpty(webApiConfig.BaseUrl); Assert.NotEmpty(webApiConfig.BaseUrl);
}
[Fact]
public void WebApiOption_Test2()
{
IOptionsMonitor<WebApiConfig> webApiMonitor = WebApiConfigManager.GetWebApiConfigOption();
Assert.NotNull(webApiMonitor);
var webApiConfig = webApiMonitor.CurrentValue;
Assert.NotNull(webApiConfig);
} }
} }
} }

@ -19,6 +19,8 @@ global using Xunit.Serialization;
global using HttpClientStudy.Model; global using HttpClientStudy.Model;
global using HttpClientStudy.Config;
global using HttpClientStudy.Core; global using HttpClientStudy.Core;
global using HttpClientStudy.Core.UseJson; global using HttpClientStudy.Core.UseJson;
global using HttpClientStudy.Core.HttpRequests; global using HttpClientStudy.Core.HttpRequests;

@ -24,9 +24,6 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\HttpClientStudy.Core\HttpClientStudy.Core.csproj" />
<ProjectReference Include="..\HttpClientStudy.Model\HttpClientStudy.Model.csproj" />
<ProjectReference Include="..\HttpClientStudy.Service\HttpClientStudy.Service.csproj" />
<ProjectReference Include="..\HttpClientStudy.WebApp\HttpClientStudy.WebApp.csproj" /> <ProjectReference Include="..\HttpClientStudy.WebApp\HttpClientStudy.WebApp.csproj" />
</ItemGroup> </ItemGroup>

@ -6,6 +6,9 @@ using System.Security.Cryptography.Xml;
using System.Text; using System.Text;
using System.Text.Unicode; using System.Text.Unicode;
using System.Threading.Tasks; using System.Threading.Tasks;
using HttpClientStudy.Config;
using Newtonsoft.Json; using Newtonsoft.Json;
namespace HttpClientStudy.UnitTest.HttpClients namespace HttpClientStudy.UnitTest.HttpClients
@ -20,7 +23,7 @@ namespace HttpClientStudy.UnitTest.HttpClients
/// </summary> /// </summary>
public static HttpClient GetHttpClient = new HttpClient() public static HttpClient GetHttpClient = new HttpClient()
{ {
BaseAddress = new Uri(WebApiConfig.WebApiBaseUrl), BaseAddress = new Uri(WebApiConfigManager.GetWebApiConfig().BaseUrl),
}; };
/// <summary> /// <summary>

@ -53,7 +53,7 @@ namespace HttpClientStudy.UnitTest.HttpClients
{ {
HttpClient httpClient = new HttpClient(); HttpClient httpClient = new HttpClient();
var responseMessage = await httpClient.GetAsync(WebApiConfig.WebApiBaseUrl + "/api/health"); var responseMessage = await httpClient.GetAsync(WebApiConfigManager.GetWebApiConfig().BaseUrl + "/api/health");
responseMessage.EnsureSuccessStatusCode(); responseMessage.EnsureSuccessStatusCode();
} }
@ -64,7 +64,7 @@ namespace HttpClientStudy.UnitTest.HttpClients
{ {
HttpClient httpClient = new HttpClient() HttpClient httpClient = new HttpClient()
{ {
BaseAddress = new Uri(WebApiConfig.WebApiBaseUrl) BaseAddress = new Uri(WebApiConfigManager.GetWebApiConfig().BaseUrl)
}; };
for (int i = 0; i < 100; i++) for (int i = 0; i < 100; i++)
{ {

@ -31,7 +31,7 @@ namespace HttpClientStudy.UnitTest.HttpClients
//构造中传入管道对象 //构造中传入管道对象
HttpClient httpClient = new HttpClient(handler); HttpClient httpClient = new HttpClient(handler);
var sd = await httpClient.GetAsync(WebApiConfig.WebApiBaseUrl + "/api/health"); var sd = await httpClient.GetAsync(WebApiConfigManager.GetWebApiConfig().BaseUrl + "/api/health");
var contentText = await sd.Content.ReadAsStringAsync(); var contentText = await sd.Content.ReadAsStringAsync();
_logger.WriteLine(contentText); _logger.WriteLine(contentText);
@ -42,7 +42,7 @@ namespace HttpClientStudy.UnitTest.HttpClients
{ {
HttpClient client = new PipelineHttpClient().CreateHttpClient(); HttpClient client = new PipelineHttpClient().CreateHttpClient();
var r = await client.GetAsync(WebApiConfig.WebApiBaseUrl + "/api/health"); var r = await client.GetAsync(WebApiConfigManager.GetWebApiConfig().BaseUrl + "/api/health");
r.EnsureSuccessStatusCode(); r.EnsureSuccessStatusCode();
} }
} }

@ -16,7 +16,7 @@
{ {
SimpleHttpClient client = new SimpleHttpClient(); SimpleHttpClient client = new SimpleHttpClient();
var result = client.Get(WebApiConfig.WebApiBaseUrl + "/api/Simple/GetAccount"); var result = client.Get(WebApiConfigManager.GetWebApiConfig().BaseUrl + "/api/Simple/GetAccount");
Assert.NotNull(result); Assert.NotNull(result);
Assert.NotEmpty(result); Assert.NotEmpty(result);
@ -27,7 +27,7 @@
{ {
SimpleHttpClient client = new SimpleHttpClient(); SimpleHttpClient client = new SimpleHttpClient();
var result = client.GetJson<BaseResult<string>>(WebApiConfig.WebApiBaseUrl + "/api/Simple/GetAccount"); var result = client.GetJson<BaseResult<string>>(WebApiConfigManager.GetWebApiConfig().BaseUrl + "/api/Simple/GetAccount");
Assert.NotNull(result); Assert.NotNull(result);
Assert.IsAssignableFrom<BaseResult>(result); Assert.IsAssignableFrom<BaseResult>(result);

@ -17,13 +17,29 @@ namespace HttpClientStudy.UnitTest
} }
[Fact] [Fact]
public async void Test() public async Task UnknownHost_Test()
{
Func<Task> func = _httpError.UnknownHostAsync;
await Assert.ThrowsAsync<HttpRequestException>(func);
}
[Fact]
public async Task Http404_Test()
{ {
var code = await _httpError.Http404Async(); var code = await _httpError.Http404Async();
Assert.Equal(HttpStatusCode.NotFound, code); Assert.Equal(HttpStatusCode.NotFound, code);
} }
[Fact]
public async Task Http500_Test()
{
var code = await _httpError.Http500Async();
Assert.Equal(HttpStatusCode.InternalServerError, code);
}
public void Dispose() public void Dispose()
{ {

@ -0,0 +1,43 @@
using System.IdentityModel.Tokens.Jwt;
using System.Net.Http.Headers;
using System.Security.Claims;
using System.Text;
using HttpClientStudy.Model;
using HttpClientStudy.WebApp.Models;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
namespace HttpClientStudy.WebApp.Controllers
{
/// <summary>
/// 错误和异常处理 控制器
/// </summary>
[Route("api/[controller]/[action]")]
[ApiController]
public class ErrorDemoController : ControllerBase
{
/// <summary>
/// 构造
/// </summary>
public ErrorDemoController() { }
/// <summary>
/// 500错误
/// </summary>
/// <returns></returns>
//[AllowAnonymous]
[HttpGet]
public IActionResult Error500()
{
throw new System.Exception("服务器异常");
var result = BaseResultUtil.Success("服务器异常");
return new JsonResult(result);
}
}
}

@ -15,8 +15,6 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\HttpClientStudy.Core\HttpClientStudy.Core.csproj" />
<ProjectReference Include="..\HttpClientStudy.Model\HttpClientStudy.Model.csproj" />
<ProjectReference Include="..\HttpClientStudy.Service\HttpClientStudy.Service.csproj" /> <ProjectReference Include="..\HttpClientStudy.Service\HttpClientStudy.Service.csproj" />
</ItemGroup> </ItemGroup>

Loading…
Cancel
Save