public void FromStream(int iteration) { #pragma warning disable CS0618 var binaryStream = BinaryHelper.ToStream(_testModel); #pragma warning restore CS0618 var dataContractStream = DataContractHelper.ToStream(_testModel); var jilStream = JilHelper.ToStream(_testModel); var messagePackStream = MessagePackHelper.ToStream(_testModel); var msgPackStream = MsgPackHelper.ToStream(_testModel); var newtonsoftJsonStream = NewtonsoftJsonHelper.ToStream(_testModel); var protobufStream = ProtobufHelper.ToStream(_testModel); var sharpYamlStream = SharpYamlHelper.ToStream(_testModel); var systemTextJsonStream = SystemTextJsonHelper.ToStream(_testModel); var utf8JsonStream = Utf8JsonHelper.ToStream(_testModel); var xmlStream = XmlHelper.ToStream(_testModel); var yamlDotNetStream = YamlDotNetHelper.ToStream(_testModel); var zeroFormatterStream = ZeroFormatterHelper.ToStream(_testModel); Console.WriteLine("FromStream go!"); Runner.Initialize(); Console.WriteLine(Runner.Time("BinaryHelper FromStream", iteration, #pragma warning disable CS0618 () => BinaryHelper.FromStream <TestModel>(binaryStream))); #pragma warning restore CS0618 Console.WriteLine(Runner.Time("DataContractHelper FromStream", iteration, () => DataContractHelper.FromStream <TestModel>(dataContractStream))); Console.WriteLine(Runner.Time("JilHelper FromStream", iteration, () => JilHelper.FromStream <TestModel>(jilStream))); Console.WriteLine(Runner.Time("MessagePackHelper FromStream", iteration, () => MessagePackHelper.FromStream <TestModel>(messagePackStream))); Console.WriteLine(Runner.Time("MsgPackHelper FromStream", iteration, () => MsgPackHelper.FromStream <TestModel>(msgPackStream))); Console.WriteLine(Runner.Time("NewtonsoftJsonHelper FromStream", iteration, () => NewtonsoftJsonHelper.FromStream <TestModel>(newtonsoftJsonStream))); Console.WriteLine(Runner.Time("ProtobufHelper FromStream", iteration, () => ProtobufHelper.FromStream <TestModel>(protobufStream))); Console.WriteLine(Runner.Time("SharpYamlHelper FromStream", iteration, () => SharpYamlHelper.FromStream <TestModel>(sharpYamlStream))); Console.WriteLine(Runner.Time("SystemTextJsonHelper FromStream", iteration, () => SystemTextJsonHelper.FromStream <TestModel>(systemTextJsonStream))); Console.WriteLine(Runner.Time("Utf8JsonHelper FromStream", iteration, () => Utf8JsonHelper.FromStream <TestModel>(utf8JsonStream))); Console.WriteLine(Runner.Time("XmlHelper FromStream", iteration, () => XmlHelper.FromStream <TestModel>(xmlStream))); Console.WriteLine(Runner.Time("YamlDotNetHelper FromStream", iteration, () => YamlDotNetHelper.FromStream <TestModel>(yamlDotNetStream))); Console.WriteLine(Runner.Time("ZeroFormatterHelper FromStream", iteration, () => ZeroFormatterHelper.FromStream <TestModel>(zeroFormatterStream))); Console.WriteLine("\r\nFromStream complete!\r\n"); }
/// <summary> /// Controllers 注册 /// Sytem.Text.Json 配置 /// FluentValidation 注册 /// ApiBehaviorOptions 配置 /// </summary> public virtual void AddControllers() { _services.AddControllers(options => options.Filters.Add(typeof(CustomExceptionFilterAttribute))) .AddJsonOptions(options => { options.JsonSerializerOptions.Converters.Add(new DateTimeConverter()); options.JsonSerializerOptions.Converters.Add(new DateTimeNullableConverter()); options.JsonSerializerOptions.Encoder = SystemTextJsonHelper.GetAdncDefaultEncoder(); //该值指示是否允许、不允许或跳过注释。 options.JsonSerializerOptions.ReadCommentHandling = JsonCommentHandling.Skip; //dynamic与匿名类型序列化设置 options.JsonSerializerOptions.PropertyNameCaseInsensitive = true; //dynamic options.JsonSerializerOptions.DictionaryKeyPolicy = JsonNamingPolicy.CamelCase; //匿名类型 options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase; }) .AddFluentValidation(cfg => { //Continue 验证失败,继续验证其他项 cfg.ValidatorOptions.CascadeMode = FluentValidation.CascadeMode.Continue; // Optionally set validator factory if you have problems with scope resolve inside validators. // cfg.ValidatorFactoryType = typeof(HttpContextServiceProviderValidatorFactory); }); //参数验证返回信息格式调整 _services.Configure <ApiBehaviorOptions>(options => { //关闭自动验证 //options.SuppressModelStateInvalidFilter = true; //格式化验证信息 options.InvalidModelStateResponseFactory = (context) => { var problemDetails = new ProblemDetails { Detail = context.ModelState.GetValidationSummary("<br>") , Title = "参数错误" , Status = (int)HttpStatusCode.BadRequest , Type = "https://httpstatuses.com/400" , Instance = context.HttpContext.Request.Path }; return(new ObjectResult(problemDetails) { StatusCode = problemDetails.Status }); }; }); }
private dynamic CreateOpsLog(string className, string methodName, string logName, object[] arguments, UserContext userContext) { dynamic log = new ExpandoObject(); log.ClassName = className; log.CreateTime = DateTime.Now; log.LogName = logName; log.LogType = "操作日志"; log.Message = JsonSerializer.Serialize(arguments, SystemTextJsonHelper.GetAdncDefaultOptions()); log.Method = methodName; log.Succeed = "false"; log.UserId = userContext.Id; log.UserName = userContext.Name; log.Account = userContext.Account; log.RemoteIpAddress = userContext.RemoteIpAddress; return(log); }
public void Intercept(IInvocation invocation) { invocation.Proceed(); var serviceMethod = invocation.Method ?? invocation.MethodInvocationTarget; var attribute = serviceMethod.GetCustomAttribute <OpsLogAttribute>(); if (attribute == null) { return; } if (_isLoging) { return; } else { _isLoging = true; } var logInfo = new { ClassName = serviceMethod.DeclaringType.FullName, CreateTime = DateTime.Now, LogName = attribute.LogName, LogType = "操作日志", Message = JsonSerializer.Serialize(invocation.Arguments, SystemTextJsonHelper.GetAdncDefaultOptions()), Method = serviceMethod.Name, Succeed = "", UserId = _userContext.ID, UserName = _userContext.Name, Account = _userContext.Account, RemoteIpAddress = _userContext.RemoteIpAddress }; var properties = _mqProducer.CreateBasicProperties(); //设置消息持久化 properties.Persistent = true; _mqProducer.BasicPublish(BaseMqExchanges.Logs, BaseMqRoutingKeys.OpsLog, logInfo, properties); }
private OperationLog CreateOpsLog(string className, string methodName, string logName, object[] arguments, IUserContext userContext) { var log = new OperationLog { ClassName = className, CreateTime = DateTime.Now, LogName = logName, LogType = "操作日志", Message = JsonSerializer.Serialize(arguments, SystemTextJsonHelper.GetAdncDefaultOptions()), Method = methodName, Succeed = "false", UserId = userContext.Id, UserName = userContext.Name, Account = userContext.Account, RemoteIpAddress = userContext.RemoteIpAddress }; return(log); }
/// <summary> /// Controllers 注册 /// Sytem.Text.Json 配置 /// FluentValidation 注册 /// ApiBehaviorOptions 配置 /// </summary> public virtual void AddControllers() { _services.AddControllers(options => options.Filters.Add(typeof(CustomExceptionFilterAttribute))) .AddJsonOptions(options => { options.JsonSerializerOptions.Converters.Add(new DateTimeConverter()); options.JsonSerializerOptions.Converters.Add(new DateTimeNullableConverter()); options.JsonSerializerOptions.Encoder = SystemTextJsonHelper.GetAdncDefaultEncoder(); //该值指示是否允许、不允许或跳过注释。 options.JsonSerializerOptions.ReadCommentHandling = JsonCommentHandling.Skip; //dynamic与匿名类型序列化设置 options.JsonSerializerOptions.PropertyNameCaseInsensitive = true; //dynamic options.JsonSerializerOptions.DictionaryKeyPolicy = JsonNamingPolicy.CamelCase; //匿名类型 options.JsonSerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase; }) .AddFluentValidation(cfg => { //Continue 验证失败,继续验证其他项 cfg.ValidatorOptions.CascadeMode = FluentValidation.CascadeMode.Continue; }); //参数验证返回信息格式调整 _services.Configure <ApiBehaviorOptions>(options => { //关闭自动验证 //options.SuppressModelStateInvalidFilter = true; //格式化验证信息 options.InvalidModelStateResponseFactory = (context) => { var result = new JsonResult(new { error = context.ModelState.GetValidationSummary("<br>") }) { StatusCode = (int)HttpStatusCode.BadRequest }; return(result); }; }); }
public override void OnException(ExceptionContext context) { Exception exception = context.Exception; JsonResult result = null; if (exception is BusinessException) { result = new JsonResult( JsonSerializer.Deserialize <ErrorModel>(exception.Message, SystemTextJsonHelper.GetAdncDefaultOptions()) , SystemTextJsonHelper.GetAdncDefaultOptions()) { StatusCode = exception.HResult }; } else { result = new JsonResult(new ErrorModel(System.Net.HttpStatusCode.InternalServerError, "服务器异常") , SystemTextJsonHelper.GetAdncDefaultOptions()) { StatusCode = (int)System.Net.HttpStatusCode.InternalServerError }; var userContext = context.HttpContext.RequestServices.GetService <UserContext>(); var descriptor = context.ActionDescriptor as ControllerActionDescriptor; string className = descriptor.ControllerName; string method = descriptor.ActionName; string requestUrl = context.HttpContext.Request.Path; long userId = userContext.ID; //var parms = ex.Data?.ToDictionary().Select(k => k.Key + "=" + k.Value).Join() ?? ""; _logger.LogError(exception, exception.Message); //Agent.Tracer.CurrentTransaction.CaptureException(exception); } context.Result = result; context.ExceptionHandled = true; }
public void ToStream(int iteration) { Console.WriteLine("ToStream go!"); Runner.Initialize(); Console.WriteLine(Runner.Time("BinaryHelper ToStream", iteration, #pragma warning disable CS0618 () => BinaryHelper.ToStream(_testModel))); #pragma warning restore CS0618 Console.WriteLine(Runner.Time("DataContractHelper ToStream", iteration, () => DataContractHelper.ToStream(_testModel))); Console.WriteLine(Runner.Time("JilHelper ToStream", iteration, () => JilHelper.ToStream(_testModel))); Console.WriteLine(Runner.Time("MessagePackHelper ToStream", iteration, () => MessagePackHelper.ToStream(_testModel))); Console.WriteLine(Runner.Time("MsgPackHelper ToStream", iteration, () => MsgPackHelper.ToStream(_testModel))); Console.WriteLine(Runner.Time("NewtonsoftJsonHelper ToStream", iteration, () => NewtonsoftJsonHelper.ToStream(_testModel))); Console.WriteLine(Runner.Time("ProtobufHelper ToStream", iteration, () => ProtobufHelper.ToStream(_testModel))); Console.WriteLine(Runner.Time("SharpYamlHelper ToStream", iteration, () => SharpYamlHelper.ToStream(_testModel))); Console.WriteLine(Runner.Time("SystemTextJsonHelper ToStream", iteration, () => SystemTextJsonHelper.ToStream(_testModel))); Console.WriteLine(Runner.Time("Utf8JsonHelper ToStream", iteration, () => Utf8JsonHelper.ToStream(_testModel))); Console.WriteLine(Runner.Time("XmlHelper ToStream", iteration, () => XmlHelper.ToStream(_testModel))); Console.WriteLine(Runner.Time("YamlDotNetHelper ToStream", iteration, () => YamlDotNetHelper.ToStream(_testModel))); Console.WriteLine(Runner.Time("ZeroFormatterHelper ToStream", iteration, () => ZeroFormatterHelper.ToStream(_testModel))); Console.WriteLine("\r\nToStream complete!\r\n"); }
public static MemoryStream ToStream(this object?value, Type type, JsonSerializerOptions?options = null) => SystemTextJsonHelper.ToStream(type, value, options);
public static MemoryStream ToStream <TValue>(this TValue?value, JsonSerializerOptions?options = null) => SystemTextJsonHelper.ToStream(value, options);
public override string ToString() { return(JsonSerializer.Serialize(this, SystemTextJsonHelper.GetAdncDefaultOptions())); }
public static object?FromBytes(this byte[]?bytes, Type type, JsonSerializerOptions?options = null) => SystemTextJsonHelper.FromBytes(type, bytes, options);
public static TValue?FromBytes <TValue>(this ReadOnlySpan <byte> bytes, JsonSerializerOptions?options = null) => SystemTextJsonHelper.FromBytes <TValue>(bytes, options);
public static TValue?FromJson <TValue>(this string?json, JsonSerializerOptions?options = null) => SystemTextJsonHelper.FromJson <TValue>(json, options);
public static string ToJson(this object?value, Type type, JsonSerializerOptions?options = null) => SystemTextJsonHelper.ToJson(type, value, options);
public static void PackBy(this Stream?stream, Type type, object?value, JsonSerializerOptions?options = null) => SystemTextJsonHelper.Pack(type, value, stream, options);
public static Task <object?> FromStreamAsync(this Stream?stream, Type type, JsonSerializerOptions?options = null, CancellationToken cancellationToken = default) => SystemTextJsonHelper.FromStreamAsync(type, stream, options, cancellationToken);
public static Task PackByAsync(this Stream?stream, Type type, object?value, JsonSerializerOptions?options = null, CancellationToken cancellationToken = default) => SystemTextJsonHelper.PackAsync(type, value, stream, options, cancellationToken);
public static Task PackToAsync <TValue>(this TValue?value, Stream?stream, JsonSerializerOptions?options = null, CancellationToken cancellationToken = default) => SystemTextJsonHelper.PackAsync(value, stream, options, cancellationToken);
public static byte[] ToBytes(this object?value, Type type, JsonSerializerOptions?options = null) => SystemTextJsonHelper.ToBytes(type, value, options);
public static byte[] ToBytes <TValue>(this TValue?value, JsonSerializerOptions?options = null) => SystemTextJsonHelper.ToBytes(value, options);
public static object?FromJson(this string?json, Type type, JsonSerializerOptions?options = null) => SystemTextJsonHelper.FromJson(type, json, options);
public static void PackBy <TValue>(this Stream?stream, TValue?value, JsonSerializerOptions?options = null) => SystemTextJsonHelper.Pack(value, stream, options);
public static TValue?FromStream <TValue>(this Stream?stream, JsonSerializerOptions?options = null) => SystemTextJsonHelper.FromStream <TValue>(stream, options);
public static Task <TValue?> FromStreamAsync <TValue>(this Stream?stream, JsonSerializerOptions?options = null, CancellationToken cancellationToken = default) => SystemTextJsonHelper.FromStreamAsync <TValue>(stream, options, cancellationToken);
public static object?FromStream(this Stream?stream, Type type, JsonSerializerOptions?options = null) => SystemTextJsonHelper.FromStream(type, stream, options);
/// <summary> /// 注册Rpc服务(跨微服务之间的同步通讯) /// </summary> /// <typeparam name="TRpcService">Rpc服务接口</typeparam> /// <param name="serviceName">在注册中心注册的服务名称,或者服务的Url</param> /// <param name="policies">Polly策略</param> public virtual void AddRpcService <TRpcService>(string serviceName , List <IAsyncPolicy <HttpResponseMessage> > policies ) where TRpcService : class, IRpcService { var prefix = serviceName.Substring(0, 7); bool isConsulAdderss = (prefix == "http://" || prefix == "https:/") ? false : true; var refitSettings = new RefitSettings(new SystemTextJsonContentSerializer(SystemTextJsonHelper.GetAdncDefaultOptions())); //注册RefitClient,设置httpclient生命周期时间,默认也是2分钟。 var clientbuilder = _services.AddRefitClient <TRpcService>(refitSettings) .SetHandlerLifetime(TimeSpan.FromMinutes(2)); //如果参数是服务名字,那么需要从consul获取地址 if (isConsulAdderss) { clientbuilder.ConfigureHttpClient(client => client.BaseAddress = new Uri($"http://{serviceName}")) .AddHttpMessageHandler <ConsulDiscoverDelegatingHandler>(); } else { clientbuilder.ConfigureHttpClient(client => client.BaseAddress = new Uri(serviceName)) .AddHttpMessageHandler <SimpleDiscoveryDelegatingHandler>(); } //添加polly相关策略 policies?.ForEach(policy => clientbuilder.AddPolicyHandler(policy)); }
public static TValue?FromBytes <TValue>(this byte[]?bytes, JsonSerializerOptions?options = null) => SystemTextJsonHelper.FromBytes <TValue>(bytes, options);
/// <summary> /// 注册Rpc服务(跨服务之间的同步通讯) /// </summary> /// <typeparam name="TRpcService">Rpc服务接口</typeparam> /// <param name="serviceName">在注册中心注册的服务名称,或者服务的Url</param> /// <param name="policies">Polly策略</param> /// <param name="token">Token,可空</param> protected virtual void AddRpcService <TRpcService>(string serviceName , List <IAsyncPolicy <HttpResponseMessage> > policies , Func <Task <string> > token = null ) where TRpcService : class, IRpcService { var prefix = serviceName.Substring(0, 7); bool isConsulAdderss = (prefix == "http://" || prefix == "https:/") ? false : true; var refitSettings = new RefitSettings(new SystemTextJsonContentSerializer(SystemTextJsonHelper.GetAdncDefaultOptions())); //注册RefitClient,设置httpclient生命周期时间,默认也是2分钟。 var clientbuilder = _services.AddRefitClient <TRpcService>(refitSettings) .SetHandlerLifetime(TimeSpan.FromMinutes(2)); //从consul获取地址 if (isConsulAdderss) { clientbuilder.ConfigureHttpClient(c => c.BaseAddress = new Uri($"http://{serviceName}")) .AddHttpMessageHandler(() => { return(new ConsulDiscoveryDelegatingHandler(_consulConfig.ConsulUrl, token)); }); } else { clientbuilder.ConfigureHttpClient((options) => { options.BaseAddress = new Uri(serviceName); }); } //添加polly相关策略 if (policies != null && policies.Any()) { foreach (var policy in policies) { clientbuilder.AddPolicyHandler(policy); } } }
public static string ToJson <TValue>(this TValue?value, JsonSerializerOptions?options = null) => SystemTextJsonHelper.ToJson(value, options);