Skip to content

Commit

Permalink
一此细节改进
Browse files Browse the repository at this point in the history
  • Loading branch information
xljiulang committed Jan 26, 2021
1 parent e8109e0 commit 7bbd6e8
Show file tree
Hide file tree
Showing 12 changed files with 112 additions and 51 deletions.
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
using System.Threading.Tasks;
using WebApiClientCore.Exceptions;
using WebApiClientCore.Extensions.JsonRpc;
using WebApiClientCore.Serialization;

namespace WebApiClientCore.Attributes
{
Expand Down Expand Up @@ -90,10 +89,9 @@ Task IApiFilter.OnRequestAsync(ApiRequestContext context)
Params = parameters.ToJsonRpcParams(this.ParamsStyle),
};

var jsonRpcContent = new JsonRpcContent(this.ContentType);
var options = context.HttpContext.HttpApiOptions.JsonSerializeOptions;
var jsonRpcContent = new JsonRpcContent(jsonRpcRequest, options, this.ContentType);
context.HttpContext.RequestMessage.Content = jsonRpcContent;
var options = context.HttpContext.HttpApiOptions.JsonSerializeOptions;
JsonBufferSerializer.Serialize(jsonRpcContent, jsonRpcRequest, options);

return Task.CompletedTask;
}
Expand Down
19 changes: 12 additions & 7 deletions WebApiClientCore.Extensions.JsonRpc/Internals/JsonRpcContent.cs
Original file line number Diff line number Diff line change
@@ -1,24 +1,29 @@
using WebApiClientCore.HttpContents;
using System.Text.Json;
using WebApiClientCore.HttpContents;
using WebApiClientCore.Serialization;

namespace WebApiClientCore.Extensions.JsonRpc
{
/// <summary>
/// 表示JsonRpc请求内容
/// </summary>
class JsonRpcContent : BufferContent
sealed class JsonRpcContent : BufferContent
{
/// <summary>
/// 获取对应的ContentType
/// </summary>
public static string MediaType => "application/json-rpc";
public static string MediaType => "application/json-rpc";

/// <summary>
/// JsonRpc请求内容
/// </summary>
/// <param name="mediaType">媒体类型</param>
public JsonRpcContent(string? mediaType)
/// uft8的json内容
/// </summary>
/// <param name="mediaType"></param>
/// <param name="value">对象值</param>
/// <param name="jsonSerializerOptions">json序列化选项</param>
public JsonRpcContent(object? value, JsonSerializerOptions? jsonSerializerOptions, string? mediaType)
: base(mediaType ?? MediaType)
{
JsonBufferSerializer.Serialize(this, value, jsonSerializerOptions);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ namespace WebApiClientCore.Extensions.JsonRpc
/// <summary>
/// 表示JsonRpc参数
/// </summary>
class JsonRpcParameters : List<ApiParameterContext>
sealed class JsonRpcParameters : List<ApiParameterContext>
{
/// <summary>
/// 转换为jsonRpc请求参数
Expand All @@ -24,6 +24,6 @@ public object ToJsonRpcParams(JsonRpcParamsStyle paramsStyle)
{
return this.ToDictionary(item => item.ParameterName, item => item.ParameterValue);
}
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ namespace WebApiClientCore.Extensions.JsonRpc
/// <summary>
/// 表示JsonRpc的请求实体
/// </summary>
class JsonRpcRequest
{
sealed class JsonRpcRequest
{
/// <summary>
/// id值
/// </summary>
Expand Down
21 changes: 20 additions & 1 deletion WebApiClientCore/ApiRequestContextExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using Microsoft.Extensions.Logging;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Net.Http;

Expand Down Expand Up @@ -95,5 +96,23 @@ internal static HttpCompletionOption GetCompletionOption(this ApiRequestContext
? HttpCompletionOption.ResponseHeadersRead
: HttpCompletionOption.ResponseContentRead;
}

/// <summary>
/// 获取指向api方法名的日志
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
internal static ILogger? GetLogger(this ApiRequestContext context)
{
var loggerFactory = context.HttpContext.ServiceProvider.GetService<ILoggerFactory>();
if (loggerFactory == null)
{
return null;
}

var method = context.ActionDescriptor.Member;
var categoryName = $"{method.DeclaringType?.Namespace}.{method.DeclaringType?.Name}.{method.Name}";
return loggerFactory.CreateLogger(categoryName);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -135,15 +135,11 @@ public sealed async override Task OnResponseAsync(ApiResponseContext context)
/// <returns></returns>
protected virtual Task WriteLogAsync(ApiResponseContext context, LogMessage logMessage)
{
var loggerFactory = context.HttpContext.ServiceProvider.GetService<ILoggerFactory>();
if (loggerFactory == null)
var logger = context.GetLogger();
if (logger == null)
{
return Task.CompletedTask;
}

var method = context.ActionDescriptor.Member;
var categoryName = $"{method.DeclaringType?.Namespace}.{method.DeclaringType?.Name}.{method.Name}";
var logger = loggerFactory.CreateLogger(categoryName);
}

if (logMessage.Exception == null)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,8 @@ public sealed override async Task OnRequestAsync(ApiParameterContext context)
var method = context.HttpContext.RequestMessage.Method;
if (method == HttpMethod.Get || method == HttpMethod.Head)
{
var loggerFactory = context.HttpContext.ServiceProvider.GetService<ILoggerFactory>();
if (loggerFactory != null)
{
var action = context.ActionDescriptor.Member;
var categoryName = $"{action.DeclaringType?.Namespace}.{action.DeclaringType?.Name}.{action.Name}";
var logger = loggerFactory.CreateLogger(categoryName);
logger.LogWarning(Resx.gethead_Content_Warning.Format(method));
}
var logger = context.GetLogger();
logger?.LogWarning(Resx.gethead_Content_Warning.Format(method));
}

await this.SetHttpContentAsync(context).ConfigureAwait(false);
Expand Down
46 changes: 46 additions & 0 deletions WebApiClientCore/BuildinExtensions/EncodingExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
using System;
using System.Buffers;
using System.Diagnostics;
using System.Text;

namespace WebApiClientCore
{
/// <summary>
/// 提供Encoding扩展
/// </summary>
static class EncodingExtensions
{
/// <summary>
/// 转换编码
/// </summary>
/// <param name="srcEncoding"></param>
/// <param name="dstEncoding">目标编码</param>
/// <param name="buffer">源内容</param>
/// <param name="writer">目标写入器</param>
public static void Convert(this Encoding srcEncoding, Encoding dstEncoding, ReadOnlySpan<byte> buffer, IBufferWriter<byte> writer)
{
var decoder = srcEncoding.GetDecoder();
var charCount = decoder.GetCharCount(buffer, false);
var charArray = ArrayPool<char>.Shared.Rent(charCount);

try
{
decoder.Convert(buffer, charArray, true, out _, out var charsUsed, out _);
Debug.Assert(charCount == charsUsed);
var chars = charArray.AsSpan().Slice(0, charsUsed);

var encoder = dstEncoding.GetEncoder();
var byteCount = encoder.GetByteCount(chars, false);
var bytes = writer.GetSpan(byteCount);

encoder.Convert(chars, bytes, true, out _, out var byteUsed, out _);
Debug.Assert(byteCount == byteUsed);
writer.Advance(byteUsed);
}
finally
{
ArrayPool<char>.Shared.Return(charArray);
}
}
}
}
2 changes: 1 addition & 1 deletion WebApiClientCore/HttpContents/FormContent.cs
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ protected override void Dispose(bool disposing)
/// <param name="httpContent">httpContent实例</param>
/// <param name="disposeHttpContent">是否释放httpContent</param>
/// <returns></returns>
public static async Task<FormContent> ParseAsync(HttpContent httpContent, bool disposeHttpContent = true)
public static async Task<FormContent> ParseAsync(HttpContent? httpContent, bool disposeHttpContent = true)
{
if (httpContent == null)
{
Expand Down
8 changes: 3 additions & 5 deletions WebApiClientCore/HttpContents/JsonContent.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,12 +48,10 @@ public JsonContent(object? value, JsonSerializerOptions? jsonSerializerOptions,
}
else
{
using var bufferWriter = new RecyclableBufferWriter<byte>();
JsonBufferSerializer.Serialize(bufferWriter, value, jsonSerializerOptions);
var utf8Json = bufferWriter.WrittenSegment;
var jsonContent = Encoding.Convert(Encoding.UTF8, encoding, utf8Json.Array, utf8Json.Offset, utf8Json.Count);
using var utf8Writer = new RecyclableBufferWriter<byte>();
JsonBufferSerializer.Serialize(utf8Writer, value, jsonSerializerOptions);

this.Write(jsonContent);
Encoding.UTF8.Convert(encoding, utf8Writer.WrittenSpan, this);
this.Headers.ContentType.CharSet = encoding.WebName;
}
}
Expand Down
18 changes: 13 additions & 5 deletions WebApiClientCore/Implementations/HttpApiRequestMessageImpl.cs
Original file line number Diff line number Diff line change
Expand Up @@ -227,17 +227,25 @@ public override void AddFormDataFile(Stream stream, string name, string? fileNam
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void EnsureMediaTypeEqual(string newMediaType)
{
var existsMediaType = this.Content?.Headers.ContentType?.MediaType;
if (string.IsNullOrEmpty(existsMediaType) == true)
if (this.Content == null)
{
return;
}

if (string.Equals(existsMediaType, newMediaType, StringComparison.OrdinalIgnoreCase) == false)
var contentType = this.Content.Headers.ContentType;
if (contentType == null)
{
var message = Resx.contenType_RemainAs.Format(existsMediaType);
throw new NotSupportedException(message);
return;
}

var oldMediaType = contentType.MediaType;
if (newMediaType.Equals(oldMediaType, StringComparison.OrdinalIgnoreCase))
{
return;
}

var message = Resx.contenType_RemainAs.Format(oldMediaType);
throw new NotSupportedException(message);
}


Expand Down
15 changes: 6 additions & 9 deletions WebApiClientCore/Parameters/JsonPatchDocument.cs
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,12 @@ private class DebugView
/// </summary>
private readonly JsonPatchDocument target;

/// <summary>
/// 查看的内容
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public List<object> Oprations => this.target.oprations;

/// <summary>
/// 调试视图
/// </summary>
Expand All @@ -99,15 +105,6 @@ public DebugView(JsonPatchDocument target)
{
this.target = target;
}

/// <summary>
/// 查看的内容
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public List<object> Oprations
{
get => this.target.oprations;
}
}
}
}

0 comments on commit 7bbd6e8

Please sign in to comment.