Browse Source

新增校验企业统一社会信用代码

懒得勤快 1 year ago
parent
commit
21fe646d06

+ 11 - 1
Masuit.Tools.Abstractions/Extensions/BaseType/StringExtensions.cs

@@ -653,6 +653,16 @@ namespace Masuit.Tools
             return Regex.IsMatch(s, @"^0\d{2,3}(?:-?\d{8}|-?\d{7})$");
         }
 
+        /// <summary>
+        /// 匹配企业的统一社会信用代码
+        /// </summary>
+        /// <param name="s">源字符串</param>
+        /// <returns>是否匹配成功</returns>
+        public static bool MatchUSCC(this string s)
+        {
+            return Regex.IsMatch(s, @"^([0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}|[1-9]\d{14})$");
+        }
+
         #endregion 校验手机号码的正确性
 
         #region Url
@@ -936,4 +946,4 @@ $", RegexOptions.IgnorePatternWhitespace | RegexOptions.IgnoreCase | RegexOption
             return new string(c);
         }
     }
-}
+}

+ 1 - 1
Masuit.Tools.Abstractions/Masuit.Tools.Abstractions.csproj

@@ -3,7 +3,7 @@
         <TargetFrameworks>netstandard2.0;netstandard2.1;net461;net5;net6;net7;net8</TargetFrameworks>
         <LangVersion>latest</LangVersion>
         <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
-        <Version>2.6.9.8</Version>
+        <Version>2.6.9.9</Version>
         <Authors>懒得勤快</Authors>
         <Description>全龄段友好的C#万能工具库,码数吐司库,不管你是菜鸟新手还是骨灰级玩家都能轻松上手,Masuit.Tools基础公共库(适用于.NET4.6.1/.NET Standard2.0及以上项目),包含一些常用的操作类,大都是静态类,加密解密,反射操作,Excel简单导出,权重随机筛选算法,分布式短id,表达式树,linq扩展,文件压缩,多线程下载和FTP客户端,硬件信息,字符串扩展方法,日期时间扩展操作,中国农历,大文件拷贝,图像裁剪,验证码,断点续传,集合扩展等常用封装。
             官网教程:https://tools.masuit.org

+ 1 - 1
Masuit.Tools.Abstractions/Validator/IsPhoneAttribute.cs

@@ -55,4 +55,4 @@ public class IsPhoneAttribute : ValidationAttribute
         ErrorMessage = _customMessage ?? "手机号码格式不正确,请输入有效的大陆11位手机号码!";
         return false;
     }
-}
+}

+ 58 - 0
Masuit.Tools.Abstractions/Validator/UnifiedSocialCreditCodeAttribute.cs

@@ -0,0 +1,58 @@
+using System.ComponentModel.DataAnnotations;
+
+namespace Masuit.Tools.Core.Validator;
+
+/// <summary>
+/// 验证企业的统一社会信用代码是否合法
+/// </summary>
+public class UnifiedSocialCreditCodeAttribute : ValidationAttribute
+{
+    /// <summary>
+    /// 是否允许为空
+    /// </summary>
+    public bool AllowEmpty { get; set; }
+
+    private readonly string _customMessage;
+
+    /// <summary>
+    ///
+    /// </summary>
+    /// <param name="customMessage">自定义错误消息</param>
+    public UnifiedSocialCreditCodeAttribute(string customMessage = null)
+    {
+        _customMessage = customMessage;
+    }
+
+    /// <summary>
+    /// 验证手机号码是否合法
+    /// </summary>
+    /// <param name="value"></param>
+    /// <returns></returns>
+    public override bool IsValid(object value)
+    {
+        if (AllowEmpty)
+        {
+            switch (value)
+            {
+                case null:
+                case string s when string.IsNullOrEmpty(s):
+                    return true;
+            }
+        }
+
+        if (value is null)
+        {
+            ErrorMessage = _customMessage ?? "企业统一社会信用代码不能为空";
+            return false;
+        }
+
+        string phone = value as string;
+        if (phone.MatchUSCC())
+        {
+            return true;
+        }
+
+        ErrorMessage = _customMessage ?? "企业统一社会信用代码格式不正确,请输入有效的企业统一社会信用代码!";
+        return false;
+    }
+}

+ 1 - 1
Masuit.Tools.AspNetCore/Masuit.Tools.AspNetCore.csproj

@@ -18,7 +18,7 @@
         <Product>Masuit.Tools.AspNetCore</Product>
         <PackageId>Masuit.Tools.AspNetCore</PackageId>
         <LangVersion>latest</LangVersion>
-        <Version>1.2.9.8</Version>
+        <Version>1.2.9.9</Version>
         <RepositoryType></RepositoryType>
         <GeneratePackageOnBuild>True</GeneratePackageOnBuild>
         <FileVersion>1.1.9</FileVersion>

+ 0 - 88
Masuit.Tools.AspNetCore/ModelBinder/BodyOrDefaultBinderMiddleware.cs

@@ -1,88 +0,0 @@
-using System.Net.Mime;
-using System.Text;
-using System.Xml.Linq;
-using Microsoft.AspNetCore.Http;
-using Microsoft.Extensions.Logging;
-using Newtonsoft.Json.Linq;
-
-namespace Masuit.Tools.AspNetCore.ModelBinder;
-
-public sealed class BodyOrDefaultBinderMiddleware(RequestDelegate next, ILogger<BodyOrDefaultBinderMiddleware> logger)
-{
-    public Task Invoke(HttpContext context)
-    {
-        var contentType = context.Request.ContentType;
-        string mediaType;
-        var charSet = "utf-8";
-        if (string.IsNullOrWhiteSpace(contentType))
-        {
-            //表单提交
-            mediaType = "application/x-www-form-urlencoded";
-        }
-        else
-        {
-            var type = new ContentType(contentType);
-            if (!string.IsNullOrWhiteSpace(type.CharSet))
-            {
-                charSet = type.CharSet;
-            }
-
-            mediaType = type.MediaType.ToLower();
-        }
-
-        var encoding = Encoding.GetEncoding(charSet);
-        if (mediaType == "application/x-www-form-urlencoded")
-        {
-            //普通表单提交
-        }
-        else if (mediaType == "multipart/form-data")
-        {
-            //带有文件的表单提交
-        }
-        else if (mediaType == "application/json")
-        {
-            var body = context.GetBodyString(encoding)?.Trim();
-            if (string.IsNullOrWhiteSpace(body))
-            {
-                return next(context);
-            }
-
-            if (!(body.StartsWith("{") && body.EndsWith("}")))
-            {
-                return next(context);
-            }
-
-            try
-            {
-                context.Items.AddOrUpdate("BodyOrDefaultModelBinder@JsonBody", _ => JObject.Parse(body), (_, _) => JObject.Parse(body));
-                return next(context);
-            }
-            catch (Exception ex)
-            {
-                logger.LogError(ex, "Parsing json failed:" + body);
-                return next(context);
-            }
-        }
-        else if (mediaType == "application/xml")
-        {
-            var body = context.GetBodyString(encoding)?.Trim();
-            if (string.IsNullOrWhiteSpace(body))
-            {
-                return next(context);
-            }
-
-            try
-            {
-                context.Items.AddOrUpdate("BodyOrDefaultModelBinder@XmlBody", _ => XDocument.Parse(body), (_, _) => XDocument.Parse(body));
-                return next(context);
-            }
-            catch (Exception ex)
-            {
-                logger.LogError(ex, "Parsing xml failed:" + body);
-                return next(context);
-            }
-        }
-
-        return next(context);
-    }
-}

+ 4 - 4
Masuit.Tools.AspNetCore/ModelBinder/FromBodyOrDefaultAttribute.cs

@@ -55,8 +55,8 @@ namespace Masuit.Tools.AspNetCore.ModelBinder
         public IConvertible DefaultValue { get; set; } = defaultValue;
 
         /// <summary>
-		/// 取值方式
-		/// </summary>
-		public BindType Type { get; set; } = type;
+        /// 取值方式
+        /// </summary>
+        public BindType Type { get; set; } = type;
     }
-}
+}

+ 0 - 16
Masuit.Tools.AspNetCore/ModelBinder/MiddlewareExtensions.cs

@@ -1,16 +0,0 @@
-using Microsoft.AspNetCore.Builder;
-
-namespace Masuit.Tools.AspNetCore.ModelBinder;
-
-public static class MiddlewareExtensions
-{
-    /// <summary>
-    /// 使用自动参数绑定中间件
-    /// </summary>
-    /// <param name="appBuilder"></param>
-    /// <returns></returns>
-    public static IApplicationBuilder UseBodyOrDefaultModelBinder(this IApplicationBuilder appBuilder)
-    {
-        return appBuilder.UseMiddleware<BodyOrDefaultBinderMiddleware>();
-    }
-}

+ 1 - 28
Masuit.Tools.AspNetCore/ModelBinder/ModelBindingContextExtension.cs

@@ -5,7 +5,6 @@ using Microsoft.AspNetCore.Mvc.Controllers;
 using Microsoft.AspNetCore.Mvc.ModelBinding;
 using Microsoft.Extensions.Primitives;
 using Newtonsoft.Json;
-using Newtonsoft.Json.Linq;
 
 namespace Masuit.Tools.AspNetCore.ModelBinder;
 
@@ -77,32 +76,6 @@ internal static class ModelBindingContextExtension
         return bodyText;
     }
 
-    /// <summary>
-    /// 尝试设置默认值
-    /// </summary>
-    /// <param name="bindingContext"></param>
-    public static bool TrySetDefaultValue(this ModelBindingContext bindingContext)
-    {
-        var attr = bindingContext.GetAttribute<FromBodyOrDefaultAttribute>();
-        if (attr.DefaultValue != null)
-        {
-            var targetValue = attr.DefaultValue.ChangeType(bindingContext.ModelType);
-            bindingContext.Result = ModelBindingResult.Success(targetValue);
-            return true;
-        }
-
-        return false;
-    }
-
-    /// <summary>
-    /// 转换为对应类型
-    /// </summary>
-    /// <param name="this"></param>
-    public static T ConvertObjectTo<T>(this object @this)
-    {
-        return (T)ConvertObject(@this, typeof(T));
-    }
-
     /// <summary>
     /// 转换为对应类型
     /// </summary>
@@ -152,4 +125,4 @@ internal static class ModelBindingContextExtension
 
         return value;
     }
-}
+}

+ 1 - 1
Masuit.Tools.Core/Masuit.Tools.Core.csproj

@@ -6,7 +6,7 @@
 官网教程:https://tools.masuit.org
 github:https://github.com/ldqk/Masuit.Tools
         </Description>
-        <Version>2.6.9.8</Version>
+        <Version>2.6.9.9</Version>
         <Copyright>Copyright © 懒得勤快</Copyright>
         <PackageProjectUrl>https://github.com/ldqk/Masuit.Tools</PackageProjectUrl>
         <PackageTags>Masuit.Tools,工具库,Utility,Crypt,Extensions</PackageTags>

+ 1 - 1
Masuit.Tools.Excel/Masuit.Tools.Excel.csproj

@@ -3,7 +3,7 @@
         <TargetFramework>netstandard2.0</TargetFramework>
         <LangVersion>latest</LangVersion>
         <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
-        <Version>1.2.9.8</Version>
+        <Version>1.2.9.9</Version>
         <Authors>懒得勤快</Authors>
         <Description>Masuit.Tools.Excel导出库,支持一些简单数据的导出,支持图片列</Description>
         <Copyright>懒得勤快</Copyright>

+ 3 - 0
Masuit.Tools.Net45/Masuit.Tools.Net45.csproj

@@ -285,6 +285,9 @@
     <Compile Include="..\Masuit.Tools.Abstractions\Validator\MinValueAttribute.cs">
       <Link>Validator\MinValueAttribute.cs</Link>
     </Compile>
+    <Compile Include="..\Masuit.Tools.Abstractions\Validator\UnifiedSocialCreditCodeAttribute.cs">
+      <Link>Validator\UnifiedSocialCreditCodeAttribute.cs</Link>
+    </Compile>
     <Compile Include="..\Masuit.Tools.Abstractions\Win32\WindowsCommand.cs">
       <Link>Win32\WindowsCommand.cs</Link>
     </Compile>

+ 1 - 1
Masuit.Tools.Net45/package.nuspec

@@ -2,7 +2,7 @@
 <package>
     <metadata>
         <id>Masuit.Tools.Net45</id>
-        <version>2.6.9.8</version>
+        <version>2.6.9.9</version>
         <title>Masuit.Tools</title>
         <authors>懒得勤快</authors>
         <owners>masuit.com</owners>

+ 1 - 1
Masuit.Tools/package.nuspec

@@ -2,7 +2,7 @@
 <package>
     <metadata>
         <id>Masuit.Tools.Net</id>
-        <version>2.6.9.8</version>
+        <version>2.6.9.9</version>
         <title>Masuit.Tools</title>
         <authors>懒得勤快</authors>
         <owners>masuit.com</owners>

+ 3 - 6
NetCoreTest/Program.cs

@@ -9,11 +9,8 @@ var app = builder.Build();
 
 if (app.Environment.IsDevelopment())
 {
-	app.UseSwagger();
-	app.UseSwaggerUI();
+    app.UseSwagger();
+    app.UseSwaggerUI();
 }
-app.UseBodyOrDefaultModelBinder();
-
 app.MapControllers();
-
-app.Run();
+app.Run();

+ 4 - 6
README.md

@@ -152,6 +152,7 @@ bool isPhoneNumber = "15205201520".MatchPhoneNumber(); // 匹配手机号
 bool isLandline = "01088888888".MatchLandline(); // 匹配座机号
 bool isIdentifyCard = "312000199502230660".MatchIdentifyCard();// 校验中国大陆身份证号
 bool isCNPatentNumber = "200410018477.9".MatchCNPatentNumber(); // 校验中国专利申请号或专利号,是否带校验位,校验位前是否带“.”,都可以校验,待校验的号码前不要带CN、ZL字样的前缀
+bool isUSCC = "200410018477.9".MatchUSCC(); // 校验企业统一社会信用代码
 ```
 
 ### 2.硬件监测(仅支持Windows,部分函数仅支持物理机模式)
@@ -549,6 +550,9 @@ public class MyClass
   
     [MinItemsCount(1)] // 检测集合元素最少1个
     public List<string> Strs { get; set; }
+  
+    [UnifiedSocialCreditCode] // 校验企业统一社会信用代码
+    public string USCC { get; set; }
 }
 ```
 
@@ -1252,12 +1256,6 @@ public class ClassDto
 PM> Install-Package Masuit.Tools.AspNetCore
 ```
 
-Startup配置:
-
-```csharp
-app.UseBodyOrDefaultModelBinder();
-```
-
 在action的参数模型前打上标记:`[FromBodyOrDefault]`即可,示例代码如下:
 
 ```csharp