WebApiClientCore PATCH请求遇到的问题笔记

客户端使用WebApiClient.JIT库时,定义调用接口时参数JsonPatchDocument来自引用Microsoft.AspNetCore.JsonPatch。
[JsonReturn]
public interface IUserApi : IHttpApi
{
    [HttpPatch("/api/User")]
    ITask<ResultModel<UserDto>> PatchUpdateByNameAsync(EnumRole rank, string name, JsonPatchDocument<UserUpdateDto> doc);
}
API项目中的接口参数JsonPatchDocument也是来自引用Microsoft.AspNetCore.JsonPatch。
[HttpPatch]
public async Task<IResultModel> PatchUpdateByName([Required] EnumRole rank, string name, [FromBody] JsonPatchDocument<UserUpdateDto> doc)
{
    //
}
客户端调用
var result = await _userApi.PatchUpdateByNameAsync(_userInfo.Rank, name, doc);

上面的PATCH请求是正常的。

当你使用WebApiClientCore库代替WebApiClient.JIT库时PATCH请求报错:{"success":false,"msg":"failed","status":400,"errors":[{"id":"","msg":"The JSON patch document was malformed and could not be parsed."}]}

查看WebApiClientCore源码发现,WebApiClientCore有定义自己的JsonPatchDocument类

/// <summary>
/// 表示将自身作为JsonPatch请求内容
/// </summary>
/// <typeparam name="T"></typeparam>
public class JsonPatchDocument<T> : JsonPatchDocument where T : class
/// <summary>
/// 表示将自身作为JsonPatch请求内容
/// </summary>
[DebuggerTypeProxy(typeof(DebugView))]
public class JsonPatchDocument : IApiParameter
{
    //
    
    /// <summary>
    /// 执行请求前
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    public Task OnRequestAsync(ApiParameterContext context)
    {
        if (context.HttpContext.RequestMessage.Method != HttpMethod.Patch)
        {
            throw new ApiInvalidConfigException(Resx.required_PatchMethod);
        }

        var options = context.HttpContext.HttpApiOptions.JsonSerializeOptions;
        context.HttpContext.RequestMessage.Content = new JsonPatchContent(this.oprations, options);

        return Task.CompletedTask;
    }
    
}
/// <summary>
/// 表示utf8的JsonPatch内容
/// </summary>
public class JsonPatchContent : BufferContent
{
    /// <summary>
    /// 获取对应的ContentType
    /// </summary>
    public static string MediaType => "application/json-patch+json";

    /// <summary>
    /// utf8的JsonPatch内容
    /// </summary>
    public JsonPatchContent()
        : base(MediaType)
    {
    }

    /// <summary>
    /// utf8的JsonPatch内容
    /// </summary>
    /// <param name="oprations">patch操作项</param>
    /// <param name="jsonSerializerOptions">json序列化选项</param> 
    public JsonPatchContent(IEnumerable<object> oprations, JsonSerializerOptions? jsonSerializerOptions)
        : base(MediaType)
    {
        JsonBufferSerializer.Serialize(this, oprations, jsonSerializerOptions);
    }
}
所以使用WebApiClientCore库的客户端 JsonPatchDocument 应该引用自 using WebApiClientCore.Parameters; api请求才能识别JsonPatch请求内容。

有关WebApiClientCore的使用参考:https://github.com/dotnetcore/WebApiClient

posted @ 2022-02-15 23:44  weichangk  阅读(215)  评论(0编辑  收藏  举报