前言
但是,我们希望在 ASP.NET Core Web API 实现中使用的还是真实的数值型 Id,方便操作;而在对外输入/输出时对 Id 进行自动加解密转换,保证安全。
类似这样:
1
2
3
4
5
|
// 请求
http://xxx.com/user/WwYQ
// id=12345
public UserDto Get(int id)
|
那么,应该如何实现呢?
自定义序列化
在输出时,我们需要自动加密 Id。
在这里,通过编写一个自定义 JsonConverter
来实现:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
public class HashIdJsonConverter : JsonConverter<int>
{
Hashids hashids = new Hashids("NiuX");//加盐
public override int Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
var str = JsonSerializer.Deserialize<string>(ref reader, options);
return hashids.Decode(str)[0];
}
public override void Write(Utf8JsonWriter writer, int value, JsonSerializerOptions options)
{
JsonSerializer.Serialize(writer, hashids.Encode(value), options);
}
}
|
运行程序,发现我们的 Id
被正常加密:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
public class UserDto
{
[JsonConverter(typeof(HashIdJsonConverter))]
public int Id { get; set; }
public string Name { get; set; }
}
[HttpGet]
public IEnumerable<UserDto> Get()
{
return new[] { new UserDto { Id = 12345, Name = "用户12345" } };
}
|

自定义模型绑定
在输入时,我们需要自动解密 Id
。
在这里,通过编写一个自定义 IModelBinder
来实现:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
public class HashIdModelBinder : IModelBinder
{
Hashids hashids = new Hashids("公众号My IO");//加盐
public Task BindModelAsync(ModelBindingContext bindingContext)
{
var modelName = bindingContext.ModelName;
var valueProviderResult = bindingContext.ValueProvider.GetValue(modelName);
var str = valueProviderResult.FirstValue;
bindingContext.Result = ModelBindingResult.Success(hashids.Decode(str)[0]);
return Task.CompletedTask;
}
}
|
运行程序,发现我们的 Id
被正常解密:
1
2
3
4
5
|
[HttpGet("{id}")]
public UserDto Get([ModelBinder(typeof(HashIdModelBinder))]int id)
{
return new UserDto { Id = id, Name = "用户"+id } ;
}
|

相关链接
https://mp.weixin.qq.com/s?__biz=MzU3MjUzNjc1Ng==&mid=2247486897&idx=1&sn=0404b383e1058aa918342e1ad0488720&chksm=fcce2f6acbb9a67c4ac989ed1f89b7bae9099a6bebe6693029e2b7848746450c9eac553831c0&scene=178&cur_album_id=1502467532329385985#rd