Skip to content

Commit 047c622

Browse files
committed
增加JsonMulitpartTextAttribute
1 parent 33ab08a commit 047c622

File tree

3 files changed

+73
-0
lines changed

3 files changed

+73
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
using System;
2+
using System.Threading.Tasks;
3+
using WebApiClient.Contexts;
4+
5+
namespace WebApiClient.Attributes
6+
{
7+
/// <summary>
8+
/// 表示参数值序列化为Json并作为x-www-form-urlencoded的字段
9+
/// </summary>
10+
[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false)]
11+
public class JsonFormFieldAttribute : Attribute, IApiParameterAttribute, IIgnoreWhenNullable
12+
{
13+
/// <summary>
14+
/// 获取或设置当值为null是否忽略提交
15+
/// 默认为false
16+
/// </summary>
17+
public bool IgnoreWhenNull { get; set; }
18+
19+
/// <summary>
20+
/// 执行前
21+
/// </summary>
22+
/// <param name="context">上下文</param>
23+
/// <param name="parameter">参数</param>
24+
/// <returns></returns>
25+
public async Task BeforeRequestAsync(ApiActionContext context, ApiParameterDescriptor parameter)
26+
{
27+
if (this.IsIgnoreWith(parameter) == false)
28+
{
29+
var options = context.HttpApiConfig.FormatOptions;
30+
var json = context.HttpApiConfig.JsonFormatter.Serialize(parameter.Value, options);
31+
var fieldName = parameter.Name;
32+
await context.RequestMessage.AddFormFieldAsync(fieldName, json);
33+
}
34+
}
35+
}
36+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
using System;
2+
using System.Threading.Tasks;
3+
using WebApiClient.Contexts;
4+
5+
namespace WebApiClient.Attributes
6+
{
7+
/// <summary>
8+
/// 表示参数值序列化为Json并作为multipart/form-data表单的一个文本项
9+
/// </summary>
10+
[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false)]
11+
public class JsonMulitpartTextAttribute : Attribute, IApiParameterAttribute, IIgnoreWhenNullable
12+
{
13+
/// <summary>
14+
/// 获取或设置当值为null是否忽略提交
15+
/// 默认为false
16+
/// </summary>
17+
public bool IgnoreWhenNull { get; set; }
18+
19+
/// <summary>
20+
/// 执行前
21+
/// </summary>
22+
/// <param name="context">上下文</param>
23+
/// <param name="parameter">参数</param>
24+
/// <returns></returns>
25+
public Task BeforeRequestAsync(ApiActionContext context, ApiParameterDescriptor parameter)
26+
{
27+
if (this.IsIgnoreWith(parameter) == false)
28+
{
29+
var options = context.HttpApiConfig.FormatOptions;
30+
var json = context.HttpApiConfig.JsonFormatter.Serialize(parameter.Value, options);
31+
var fieldName = parameter.Name;
32+
context.RequestMessage.AddMulitpartText(fieldName, json);
33+
}
34+
return ApiTask.CompletedTask;
35+
}
36+
}
37+
}

WebApiClient/WebApiClient.csproj

0 Bytes
Binary file not shown.

0 commit comments

Comments
 (0)