!40 性能优化:移除对 Json.NET的 依赖使用 System.Text.Json 组件

Merge pull request !40 from Argo/dev-Json
This commit is contained in:
Argo 2019-10-03 16:07:44 +08:00 committed by Gitee
commit 71482a79d8
12 changed files with 43 additions and 60 deletions

View File

@ -38,7 +38,7 @@
function runUnitTest() { function runUnitTest() {
write-host "dotnet test test\UnitTest" -ForegroundColor Cyan write-host "dotnet test test\UnitTest" -ForegroundColor Cyan
dotnet test test\UnitTest --filter "(FullyQualifiedName!~MySql) & (FullyQualifiedName!~Api.SqlServer) & (FullyQualifiedName!~Api.SQLite)" /p:CollectCoverage=true /p:CoverletOutputFormat=opencover /p:Include="[Bootstrap*]*" /p:ExcludeByFile="..\..\src\admin\Bootstrap.Admin\Program.cs%2c..\..\src\admin\Bootstrap.Admin\Startup.cs%2c..\..\src\admin\Bootstrap.Admin\HttpHeaderOperation.cs" /p:CoverletOutput=..\..\ dotnet test test\UnitTest --filter "FullyQualifiedName!~MySql" /p:CollectCoverage=true /p:CoverletOutputFormat=opencover /p:Include="[Bootstrap*]*" /p:ExcludeByFile="..\..\src\admin\Bootstrap.Admin\Program.cs%2c..\..\src\admin\Bootstrap.Admin\Startup.cs%2c..\..\src\admin\Bootstrap.Admin\HttpHeaderOperation.cs" /p:CoverletOutput=..\..\
} }
function coverallUnitTest() { function coverallUnitTest() {

View File

@ -4,7 +4,7 @@
<TargetFramework>netcoreapp3.0</TargetFramework> <TargetFramework>netcoreapp3.0</TargetFramework>
<AddRazorSupportForMvc>true</AddRazorSupportForMvc> <AddRazorSupportForMvc>true</AddRazorSupportForMvc>
</PropertyGroup> </PropertyGroup>
<PropertyGroup> <PropertyGroup>
<DocumentationFile>$(MSBuildProjectName).xml</DocumentationFile> <DocumentationFile>$(MSBuildProjectName).xml</DocumentationFile>
<DockerDefaultTargetOS>Windows</DockerDefaultTargetOS> <DockerDefaultTargetOS>Windows</DockerDefaultTargetOS>
@ -12,17 +12,13 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="Bootstrap.Security.DataAccess" Version="2.2.21" /> <PackageReference Include="Bootstrap.Security.DataAccess" Version="2.2.21" />
<PackageReference Include="Bootstrap.Security.Mvc" Version="3.0.1-beta5" /> <PackageReference Include="Bootstrap.Security.Mvc" Version="3.0.1-beta6" />
<PackageReference Include="Longbow" Version="3.0.0-beta1" />
<PackageReference Include="Longbow.Configuration" Version="2.2.7" /> <PackageReference Include="Longbow.Configuration" Version="2.2.7" />
<PackageReference Include="Longbow.Logging" Version="3.0.0" /> <PackageReference Include="Longbow.Logging" Version="3.0.0" />
<PackageReference Include="Longbow.Tasks" Version="2.2.24" /> <PackageReference Include="Longbow.Tasks" Version="2.2.24" />
<PackageReference Include="Longbow.Web" Version="3.0.0-beta1" /> <PackageReference Include="Longbow.Web" Version="3.0.0-beta1" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning" Version="4.0.0-preview8.19405.7" /> <PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning" Version="4.0.0-preview8.19405.7" />
<PackageReference Include="Microsoft.AspNetCore.SignalR.Protocols.NewtonsoftJson" Version="3.0.0" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="3.0.0" /> <PackageReference Include="Microsoft.Extensions.Hosting" Version="3.0.0" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.2" />
<PackageReference Include="Sentry.AspNetCore" Version="2.0.0-beta4" /> <PackageReference Include="Sentry.AspNetCore" Version="2.0.0-beta4" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="5.0.0-rc4" /> <PackageReference Include="Swashbuckle.AspNetCore" Version="5.0.0-rc4" />
<PackageReference Include="System.Data.SqlClient" Version="4.7.0" /> <PackageReference Include="System.Data.SqlClient" Version="4.7.0" />

View File

@ -1,4 +1,4 @@
using Bootstrap.Admin.Query; using Bootstrap.Admin.Query;
using Bootstrap.DataAccess; using Bootstrap.DataAccess;
using Bootstrap.Security; using Bootstrap.Security;
using Longbow.Web.Mvc; using Longbow.Web.Mvc;
@ -47,4 +47,4 @@ namespace Bootstrap.Admin.Controllers.Api
return DictHelper.Delete(value); return DictHelper.Delete(value);
} }
} }
} }

View File

@ -29,16 +29,15 @@ namespace Bootstrap.Admin.Controllers.Api
/// <summary> /// <summary>
/// JWT 登陆认证接口 /// JWT 登陆认证接口
/// </summary> /// </summary>
/// <param name="value"></param> /// <param name="user"></param>
/// <returns></returns> /// <returns></returns>
[AllowAnonymous] [AllowAnonymous]
[HttpPost] [HttpPost]
public string Post([FromBody]JObject value) public string Post([FromBody]User user)
{ {
string token = null; var token = string.Empty;
dynamic user = value; string userName = user.UserName;
string userName = user.userName; string password = user.Password;
string password = user.password;
if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(password) && UserHelper.Authenticate(userName, password)) if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(password) && UserHelper.Authenticate(userName, password))
{ {
token = BootstrapAdminJwtTokenHandler.CreateToken(userName); token = BootstrapAdminJwtTokenHandler.CreateToken(userName);

View File

@ -11,8 +11,6 @@ using Microsoft.AspNetCore.Mvc.Versioning;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Hosting;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System; using System;
using System.Text.Encodings.Web; using System.Text.Encodings.Web;
using System.Text.Unicode; using System.Text.Unicode;
@ -59,11 +57,7 @@ namespace Bootstrap.Admin
services.AddDbAdapter(); services.AddDbAdapter();
services.AddIPLocator(DictHelper.ConfigIPLocator); services.AddIPLocator(DictHelper.ConfigIPLocator);
services.AddOnlineUsers(); services.AddOnlineUsers();
services.AddSignalR().AddNewtonsoftJsonProtocol(op => services.AddSignalR().AddJsonProtocol(op => op.PayloadSerializerOptions.Configure());
{
op.PayloadSerializerSettings.ContractResolver = new DefaultContractResolver();
op.PayloadSerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
});
services.AddSignalRExceptionFilterHandler<SignalRHub>(async (client, ex) => await client.SendMessageBody(ex).ConfigureAwait(false)); services.AddSignalRExceptionFilterHandler<SignalRHub>(async (client, ex) => await client.SendMessageBody(ex).ConfigureAwait(false));
services.AddResponseCompression(); services.AddResponseCompression();
services.AddBootstrapAdminAuthentication().AddGitee(OAuthHelper.Configure).AddGitHub(OAuthHelper.Configure); services.AddBootstrapAdminAuthentication().AddGitee(OAuthHelper.Configure).AddGitHub(OAuthHelper.Configure);
@ -77,12 +71,7 @@ namespace Bootstrap.Admin
{ {
options.Filters.Add<ExceptionFilter>(); options.Filters.Add<ExceptionFilter>();
options.Filters.Add<SignalRExceptionFilter<SignalRHub>>(); options.Filters.Add<SignalRExceptionFilter<SignalRHub>>();
}).AddNewtonsoftJson(op => }).AddJsonOptions(op => op.JsonSerializerOptions.Configure());
{
op.SerializerSettings.ContractResolver = new DefaultContractResolver();
op.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
JsonConvert.DefaultSettings = () => op.SerializerSettings;
});
services.AddApiVersioning(option => services.AddApiVersioning(option =>
{ {
option.DefaultApiVersion = new ApiVersion(1, 0); option.DefaultApiVersion = new ApiVersion(1, 0);
@ -117,9 +106,8 @@ namespace Bootstrap.Admin
app.UseStaticFiles(); app.UseStaticFiles();
app.UseAutoGenerateDatabase(); app.UseAutoGenerateDatabase();
app.UseRouting(); app.UseRouting();
app.UseAuthentication(); app.UseBootstrapAdminAuthentication(RoleHelper.RetrievesByUserName, RoleHelper.RetrievesByUrl, AppHelper.RetrievesByUserName);
app.UseAuthorization(); app.UseAuthorization();
app.UseBootstrapAdminAuthorization(RoleHelper.RetrievesByUserName, RoleHelper.RetrievesByUrl, AppHelper.RetrievesByUserName);
app.UseSwagger(Configuration["SwaggerPathBase"].TrimEnd('/')); app.UseSwagger(Configuration["SwaggerPathBase"].TrimEnd('/'));
app.UseBootstrapHealthChecks(); app.UseBootstrapHealthChecks();
app.UseOnlineUsers(TraceHelper.Filter, TraceHelper.Save); app.UseOnlineUsers(TraceHelper.Filter, TraceHelper.Save);

View File

@ -4,13 +4,9 @@
<TargetFrameworks>netcoreapp3.0;netstandard2.0</TargetFrameworks> <TargetFrameworks>netcoreapp3.0;netstandard2.0</TargetFrameworks>
</PropertyGroup> </PropertyGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'netcoreapp3.0'">
<FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Bootstrap.Security.DataAccess" Version="2.2.21" /> <PackageReference Include="Bootstrap.Security.DataAccess" Version="2.2.21" />
<PackageReference Include="Longbow" Version="3.0.0-beta1" /> <PackageReference Include="Longbow" Version="3.0.0-beta3" />
<PackageReference Include="Longbow.Configuration" Version="2.2.7" /> <PackageReference Include="Longbow.Configuration" Version="2.2.7" />
<PackageReference Include="Longbow.Data" Version="2.3.8" /> <PackageReference Include="Longbow.Data" Version="2.3.8" />
<PackageReference Include="Longbow.GiteeAuth" Version="2.2.0" /> <PackageReference Include="Longbow.GiteeAuth" Version="2.2.0" />

View File

@ -1,5 +1,4 @@
using Microsoft.AspNetCore.WebUtilities; using Microsoft.AspNetCore.WebUtilities;
using Newtonsoft.Json;
using System; using System;
using System.Collections.Concurrent; using System.Collections.Concurrent;
using System.Collections.Generic; using System.Collections.Generic;
@ -8,6 +7,12 @@ using System.Net.Http;
using System.Security.Cryptography; using System.Security.Cryptography;
using System.Text; using System.Text;
using System.Threading; using System.Threading;
#if NETCOREAPP3_0
using System.Text.Json;
#else
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
#endif
namespace Bootstrap.DataAccess namespace Bootstrap.DataAccess
{ {
@ -38,7 +43,14 @@ namespace Bootstrap.DataAccess
var url = QueryHelpers.AddQueryString("http://open.bluegoon.com/api/sms/sendcode", requestParameters); var url = QueryHelpers.AddQueryString("http://open.bluegoon.com/api/sms/sendcode", requestParameters);
var req = await client.GetAsync(url); var req = await client.GetAsync(url);
var content = await req.Content.ReadAsStringAsync(); var content = await req.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<SMSResult>(content); #if NETCOREAPP3_0
var result = JsonSerializer.Deserialize<SMSResult>(content, new JsonSerializerOptions()
{
PropertyNameCaseInsensitive = true
});
#else
var result = JsonConvert.DeserializeObject<SMSResult>(content, new JsonSerializerSettings() { ContractResolver = new DefaultContractResolver() });
#endif
var ret = false; var ret = false;
if (result.Code == "1") if (result.Code == "1")
{ {

View File

@ -6,6 +6,7 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="Bootstrap.Security.DataAccess" Version="2.2.21" /> <PackageReference Include="Bootstrap.Security.DataAccess" Version="2.2.21" />
<PackageReference Include="Longbow" Version="3.0.0-beta3" />
<PackageReference Include="Longbow.Cache" Version="2.2.15" /> <PackageReference Include="Longbow.Cache" Version="2.2.15" />
<PackageReference Include="Longbow.Configuration" Version="2.2.7" /> <PackageReference Include="Longbow.Configuration" Version="2.2.7" />
<PackageReference Include="Longbow.Data" Version="2.3.8" /> <PackageReference Include="Longbow.Data" Version="2.3.8" />

View File

@ -6,10 +6,9 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Bootstrap.Security.Mvc" Version="3.0.1-beta4" /> <PackageReference Include="Bootstrap.Security.Mvc" Version="3.0.1-beta6" />
<PackageReference Include="Longbow.Configuration" Version="2.2.7" /> <PackageReference Include="Longbow.Configuration" Version="2.2.7" />
<PackageReference Include="Microsoft.Data.Sqlite" Version="3.0.0" /> <PackageReference Include="Microsoft.Data.Sqlite" Version="3.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.0.0" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View File

@ -9,8 +9,6 @@ using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Hosting;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System; using System;
namespace Bootstrap.Client namespace Bootstrap.Client
@ -62,12 +60,7 @@ namespace Bootstrap.Client
{ {
options.Filters.Add<ExceptionFilter>(); options.Filters.Add<ExceptionFilter>();
options.Filters.Add<SignalRExceptionFilter<SignalRHub>>(); options.Filters.Add<SignalRExceptionFilter<SignalRHub>>();
}).AddNewtonsoftJson(op => }).AddJsonOptions(op => op.JsonSerializerOptions.Configure());
{
op.SerializerSettings.ContractResolver = new DefaultContractResolver();
op.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
JsonConvert.DefaultSettings = () => op.SerializerSettings;
});
} }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
@ -97,9 +90,8 @@ namespace Bootstrap.Client
app.UseCookiePolicy(); app.UseCookiePolicy();
app.UseRouting(); app.UseRouting();
app.UseAuthentication(); app.UseBootstrapAdminAuthentication(RoleHelper.RetrievesByUserName, RoleHelper.RetrievesByUrl, AppHelper.RetrievesByUserName);
app.UseAuthorization(); app.UseAuthorization();
app.UseBootstrapAdminAuthorization(RoleHelper.RetrievesByUserName, RoleHelper.RetrievesByUrl, AppHelper.RetrievesByUserName);
app.UseCacheManager(); app.UseCacheManager();
app.UseOnlineUsers(callback: TraceHelper.Save); app.UseOnlineUsers(callback: TraceHelper.Save);
app.UseEndpoints(endpoints => app.UseEndpoints(endpoints =>

View File

@ -8,8 +8,8 @@ using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Diagnostics.HealthChecks;
using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Hosting;
using Newtonsoft.Json;
using System.Net.Http; using System.Net.Http;
using System.Text.Json;
using UnitTest; using UnitTest;
using Xunit; using Xunit;
@ -85,8 +85,7 @@ namespace Bootstrap.Admin.Api
services.AddCacheManager(); services.AddCacheManager();
services.AddConfigurationManager(); services.AddConfigurationManager();
services.AddDbAdapter(); services.AddDbAdapter();
var builder = services.AddHealthChecks(); services.AddHealthChecks().AddCheck<DBHealthCheck>("db");
builder.AddCheck<DBHealthCheck>("db");
services.AddControllers(); services.AddControllers();
} }
@ -101,10 +100,10 @@ namespace Bootstrap.Admin.Api
}); });
app.UseEndpoints(builder => builder.MapHealthChecks("/Healths", new HealthCheckOptions() app.UseEndpoints(builder => builder.MapHealthChecks("/Healths", new HealthCheckOptions()
{ {
ResponseWriter = (context, report) => ResponseWriter = async (context, report) =>
{ {
context.Response.ContentType = "application/json"; context.Response.ContentType = "application/json";
return context.Response.WriteAsync(JsonConvert.SerializeObject(new { report.Entries.Keys, Report = report })); await context.Response.WriteAsync(JsonSerializer.Serialize(new { report.Status, report.TotalDuration }));
}, },
ResultStatusCodes = ResultStatusCodes =
{ {

View File

@ -1,6 +1,7 @@
using Newtonsoft.Json; using Microsoft.Extensions.DependencyInjection;
using System.Net.Http; using System.Net.Http;
using System.Net.Http.Headers; using System.Net.Http.Headers;
using System.Text.Json;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace Bootstrap.Admin namespace Bootstrap.Admin
@ -18,7 +19,7 @@ namespace Bootstrap.Admin
{ {
var resp = await client.GetAsync(requestUri); var resp = await client.GetAsync(requestUri);
var json = await resp.Content.ReadAsStringAsync(); var json = await resp.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<T>(json); return JsonSerializer.Deserialize<T>(json, new JsonSerializerOptions().Configure());
} }
/// <summary> /// <summary>
@ -34,7 +35,7 @@ namespace Bootstrap.Admin
{ {
var resp = await client.PostAsJsonAsync(requestUri, t); var resp = await client.PostAsJsonAsync(requestUri, t);
var json = await resp.Content.ReadAsStringAsync(); var json = await resp.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<TRet>(json); return JsonSerializer.Deserialize<TRet>(json, new JsonSerializerOptions().Configure());
} }
/// <summary> /// <summary>
@ -59,12 +60,12 @@ namespace Bootstrap.Admin
public static async Task<TRet> DeleteAsJsonAsync<TValue, TRet>(this HttpClient client, string requestUri, TValue t) public static async Task<TRet> DeleteAsJsonAsync<TValue, TRet>(this HttpClient client, string requestUri, TValue t)
{ {
var req = new HttpRequestMessage(HttpMethod.Delete, requestUri); var req = new HttpRequestMessage(HttpMethod.Delete, requestUri);
req.Content = new StringContent(JsonConvert.SerializeObject(t)); req.Content = new StringContent(JsonSerializer.Serialize(t));
req.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); req.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var resp = await client.SendAsync(req); var resp = await client.SendAsync(req);
var json = await resp.Content.ReadAsStringAsync(); var json = await resp.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<TRet>(json); return JsonSerializer.Deserialize<TRet>(json, new JsonSerializerOptions().Configure());
} }
/// <summary> /// <summary>
@ -90,7 +91,7 @@ namespace Bootstrap.Admin
{ {
var resp = await client.PutAsJsonAsync(requestUri, t); var resp = await client.PutAsJsonAsync(requestUri, t);
var json = await resp.Content.ReadAsStringAsync(); var json = await resp.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<TRet>(json); return JsonSerializer.Deserialize<TRet>(json, new JsonSerializerOptions().Configure());
} }
/// <summary> /// <summary>