Skip to content

Commit

Permalink
增加JsonMulitpartTextAttribute
Browse files Browse the repository at this point in the history
  • Loading branch information
xljiulang committed Mar 15, 2019
1 parent 33ab08a commit 047c622
Show file tree
Hide file tree
Showing 3 changed files with 73 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using System;
using System.Threading.Tasks;
using WebApiClient.Contexts;

namespace WebApiClient.Attributes
{
/// <summary>
/// 表示参数值序列化为Json并作为x-www-form-urlencoded的字段
/// </summary>
[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false)]
public class JsonFormFieldAttribute : Attribute, IApiParameterAttribute, IIgnoreWhenNullable
{
/// <summary>
/// 获取或设置当值为null是否忽略提交
/// 默认为false
/// </summary>
public bool IgnoreWhenNull { get; set; }

/// <summary>
/// 执行前
/// </summary>
/// <param name="context">上下文</param>
/// <param name="parameter">参数</param>
/// <returns></returns>
public async Task BeforeRequestAsync(ApiActionContext context, ApiParameterDescriptor parameter)
{
if (this.IsIgnoreWith(parameter) == false)
{
var options = context.HttpApiConfig.FormatOptions;
var json = context.HttpApiConfig.JsonFormatter.Serialize(parameter.Value, options);
var fieldName = parameter.Name;
await context.RequestMessage.AddFormFieldAsync(fieldName, json);
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
using System;
using System.Threading.Tasks;
using WebApiClient.Contexts;

namespace WebApiClient.Attributes
{
/// <summary>
/// 表示参数值序列化为Json并作为multipart/form-data表单的一个文本项
/// </summary>
[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false)]
public class JsonMulitpartTextAttribute : Attribute, IApiParameterAttribute, IIgnoreWhenNullable
{
/// <summary>
/// 获取或设置当值为null是否忽略提交
/// 默认为false
/// </summary>
public bool IgnoreWhenNull { get; set; }

/// <summary>
/// 执行前
/// </summary>
/// <param name="context">上下文</param>
/// <param name="parameter">参数</param>
/// <returns></returns>
public Task BeforeRequestAsync(ApiActionContext context, ApiParameterDescriptor parameter)
{
if (this.IsIgnoreWith(parameter) == false)
{
var options = context.HttpApiConfig.FormatOptions;
var json = context.HttpApiConfig.JsonFormatter.Serialize(parameter.Value, options);
var fieldName = parameter.Name;
context.RequestMessage.AddMulitpartText(fieldName, json);
}
return ApiTask.CompletedTask;
}
}
}
Binary file modified WebApiClient/WebApiClient.csproj
Binary file not shown.

0 comments on commit 047c622

Please sign in to comment.