From b5eeb1114e29b90bb2c660f104d376a185ae1b68 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=87=E9=9B=85=E8=99=8E?= Date: Wed, 18 Oct 2023 21:48:51 +0800 Subject: [PATCH] #14 --- Biwen.QuickApi.DemoWeb/Apis/HelloApi.cs | 7 +++++++ Biwen.QuickApi/IReqBinder.cs | 11 ++++------- 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/Biwen.QuickApi.DemoWeb/Apis/HelloApi.cs b/Biwen.QuickApi.DemoWeb/Apis/HelloApi.cs index f6295558..cf76d277 100644 --- a/Biwen.QuickApi.DemoWeb/Apis/HelloApi.cs +++ b/Biwen.QuickApi.DemoWeb/Apis/HelloApi.cs @@ -65,6 +65,10 @@ public class HelloApiRequest : AuthRequest [FromQuery(Name = "member")] public Member CurrentMember { get; set; } + [Description("header比如{\"id\":\"123\",\"userName\":\"vipwan\"}")] + [FromHeader(Name = "headmember")] + public Member CurrentMemberFromHeader { get; set; } + public record Member(string Id,string UserName); @@ -77,6 +81,9 @@ public HelloApiRequest() RuleFor(x => x.Name).NotNull().Length(2, 36); RuleFor(x => x.Password).NotNull().Length(2, 36); RuleFor(x => x.UserName).EmailAddress();//要求邮箱 + //嵌套对象验证 + RuleFor(x=>x.CurrentMember.UserName).EmailAddress(); + RuleFor(x=>x.CurrentMemberFromHeader.UserName).EmailAddress(); } } diff --git a/Biwen.QuickApi/IReqBinder.cs b/Biwen.QuickApi/IReqBinder.cs index 775525b5..db82ee5b 100644 --- a/Biwen.QuickApi/IReqBinder.cs +++ b/Biwen.QuickApi/IReqBinder.cs @@ -102,10 +102,10 @@ public virtual async Task BindAsync(HttpContext context) { var name = fromHeader.Name ?? prop.Name; var qs = context.Request.Headers; - if (qs.TryGetValue(name, out Microsoft.Extensions.Primitives.StringValues val)) + if (qs.TryGetValue(name, out StringValues val)) { //转换 - var value = TypeDescriptor.GetConverter(prop.PropertyType).ConvertFromInvariantString(val.ToString()); + var value = StringValuesExtensions.DeserializeJsonArrayString(val, prop.PropertyType); prop.SetValue(@default, value); continue; } @@ -366,7 +366,6 @@ static class StringValuesExtensions PropertyNameCaseInsensitive = true }; - /// /// 将QueryString转换为数组 /// @@ -377,7 +376,6 @@ static class StringValuesExtensions { if (input is not StringValues vals || vals.Count == 0) return null; - if (vals.Count == 1 && vals[0]!.StartsWith('[') && vals[0]!.EndsWith(']')) { // querystring: ?ids=[1,2,3] @@ -388,13 +386,12 @@ static class StringValuesExtensions return JsonSerializer.Deserialize(vals[0]!, tProp, _serializerOptions); } - //如果是单个对象且不是字符串,则直接返回 + //?user={"id":"123","name":"x"} if (tProp != typeof(string) && !tProp.GetInterfaces().Any(x => x == typeof(IEnumerable))) { return JsonSerializer.Deserialize(vals[0]!, tProp, _serializerOptions); - } - + } // querystring: ?ids=one&ids=two // possible inputs: // - 1 (as StringValues)