Compare commits

..
10 Commits
Author SHA1 Message Date
chfei 2f406c840f 云数据模块修改 2026-09-24 16:41:48 +08:00
chfei 707eb5664a Merge branch 'master' of https://github.com/KJD2025/StoreHub 2026-09-23 18:48:08 +08:00
chfei c7fb447034 修改 Startup 加载 和Module 加载 2026-09-23 18:47:54 +08:00
chfei 03dd9b8f6b test 2026-09-19 09:51:55 +08:00
chfei c732ecb1d2 gx 配置 2026-09-18 19:22:49 +08:00
chfei 0e1620c1f9 模型注册 2026-09-18 19:17:11 +08:00
chfei 75d0e85218 gx 2026-09-18 18:57:24 +08:00
chfei f2caec6083 更新框架,增加云库搜索模块 2026-09-18 18:40:10 +08:00
chfei 8526e5e0d2 更新 JWT 2026-08-28 15:31:45 +08:00
chfei f84c4c1949 增加老版本 KJDWebService 2026-08-21 16:46:36 +08:00
199 changed files with 40518 additions and 533 deletions

No files matched your search

+1 -1
View File
@@ -1,6 +1,6 @@
using MAX.Core.DependencyInjection;
using MAX.Core.Infrastructure;
using MAX.Core.Interfaces;
using System;
using System.Collections.Concurrent;
using System.Linq;
@@ -1,10 +1,12 @@
namespace MAX.Core.DependencyInjection;
using MAX.Core.Interfaces;
namespace MAX.Core.DependencyInjection;
/// <summary>
/// 依赖注册器:把当前模块的服务注册到 <see cref="IServiceRegistrar"/>。
/// 底层使用哪个容器由宿主项目决定,MAX.Core 不引用任何容器。
/// </summary>
public interface IDependencyRegistrar
public interface IDependencyRegistrar: IPriority
{
/// <summary>
/// 注册服务
+33
View File
@@ -0,0 +1,33 @@
namespace MAX.Core.Interfaces;
public interface IPriority
{
/// <summary> 优先级(优先级越高越先执行) </summary>
int Priority { get; }
}
public static class IntPriority
{
public const int Highest = 5000;
public const int VeryHigh = 4000;
public const int Higher = 3000;
public const int High = 2000;
public const int AboveNormal = 1000;
public const int Normal = 0;
public const int BelowNormal = -1000;
public const int Low = -2000;
public const int Lower = -3000;
public const int VeryLow = -4000;
public const int Lowest = -5000;
}
@@ -1,18 +1,19 @@
using MAX.Core.DependencyInjection;
using System;
using System.ComponentModel;
using System.Threading.Tasks;
namespace MAX.Core.Infrastructure;
namespace MAX.Core.Interfaces;
/// <summary>
/// 启动器:实现 <see cref="IDependencyRegistrar"/>,由宿主项目统一发现并按 <see cref="Priority"/> 排序执行。
/// </summary>
public interface IStartup : IDependencyRegistrar
{
/// <summary>
/// 优先级(优先级越高越先执行)
/// </summary>
int Priority { get; }
/// <summary>
/// 初始化
/// </summary>
void Initialize();
void Start(IServiceProvider serviceProvider);
}
@@ -1,7 +1,7 @@
using System;
using System.Reflection;
namespace MAX.Core.Infrastructure;
namespace MAX.Core.Interfaces;
/// <summary>
/// 单例,需要在当前类中定义
+1 -2
View File
@@ -1,5 +1,4 @@
using MAX.Core.Infrastructure;
namespace MAX.Core.Logger;
/// <summary>自定义日志记录器接口</summary>
+7 -1
View File
@@ -24,7 +24,8 @@
*/
using MAX.Core.DependencyInjection;
using MAX.Core.Infrastructure;
using MAX.Core.Interfaces;
using System;
namespace MAX.Core;
@@ -42,4 +43,9 @@ public class Startup : IStartup
// 示例:恢复 LazyServiceProvider 后,可在这里注册为单例
// registrar.RegisterSingleton<ILazyServiceProvider, LazyServiceProvider>();
}
public void Start(IServiceProvider serviceProvider)
{
}
}
@@ -0,0 +1,18 @@
using MAX.Framework.Dtos;
using System;
using System.Collections.Generic;
using System.Text;
namespace MAX.Framework.Commons
{
public class AppException : Exception
{
public int Code { get; }
public AppException(string message, int code = ResultCode.BusinessError)
: base(message)
{
Code = code;
}
}
}
@@ -0,0 +1,42 @@
using MAX.Framework.Dtos;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;
namespace MAX.Framework.Commons
{
public class GlobalExceptionFilter : IExceptionFilter
{
private readonly ILogger<GlobalExceptionFilter> _logger;
public GlobalExceptionFilter(ILogger<GlobalExceptionFilter> logger)
{
_logger = logger;
}
public void OnException(ExceptionContext context)
{
var traceId = context.HttpContext.TraceIdentifier;
var result = context.Exception switch
{
AppException be => ApiResult.Fail(be.Message, be.Code),
ValidationException ve => ApiResult.Fail(ve.Message, ResultCode.ValidationError),
UnauthorizedAccessException => ApiResult.Fail("未授权访问", ResultCode.Unauthorized),
_ => ApiResult.Fail("服务器内部错误", ResultCode.ServerError)
};
_logger.LogError(context.Exception, "请求异常 TraceId: {TraceId}", traceId);
context.Result = new ObjectResult(result)
{
StatusCode = 200 // 关键:HTTP状态码统一200,业务状态用Code表达
};
context.ExceptionHandled = true;
}
}
}
+26
View File
@@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace MAX.Framework.Commons
{
public class PageData<T>
{
public long Total { get; set; }
public int PageIndex { get; set; }
public int PageSize { get; set; }
public int TotalPages => PageSize > 0 ? (int)Math.Ceiling((double)Total / PageSize) : 0;
public List<T> List { get; set; } = new();
public PageData() { }
public PageData(List<T> list, long total, int pageIndex, int pageSize)
{
List = list;
Total = total;
PageIndex = pageIndex;
PageSize = pageSize;
}
}
}
@@ -0,0 +1,52 @@
using MAX.Framework.Dtos;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Text;
namespace MAX.Framework.Commons
{
/// <summary>
/// 返回过滤
/// </summary>
public class UnifyResultFilter : IActionFilter
{
public void OnActionExecuted(ActionExecutedContext context)
{
if (context.Result is ObjectResult objResult)
{
if (!IsAlreadyWrapped(objResult.Value))
{
var apiResult = ApiResult<object>.Success(objResult.Value);
objResult.Value = apiResult;
objResult.DeclaredType = null;
}
}
else if (context.Result is EmptyResult || context.Result is NoContentResult)
{
context.Result = new ObjectResult(ApiResult.Success());
}
}
public void OnActionExecuting(ActionExecutingContext context) { }
private static bool IsAlreadyWrapped(object? value)
{
if (value is null) return false;
var type = value.GetType();
// 递归判断:只要类型链上有任何一层是 ApiResult<> 的开放泛型定义,或直接是 ApiResult,就算已包装
while (type is not null)
{
if (type == typeof(ApiResult)) return true;
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(ApiResult<>)) return true;
type = type.BaseType;
}
return false;
}
}
}
@@ -0,0 +1,53 @@
using MAX.Framework.Dtos;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.Json;
namespace MAX.Framework.Commons
{
public class UnsupportedMediaTypeHandlingMiddleware
{
private readonly RequestDelegate _next;
public UnsupportedMediaTypeHandlingMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
// 用一个内存流替换原始的Response.Body,方便判断状态码后决定是否要改写
var originalBodyStream = context.Response.Body;
using var memoryStream = new MemoryStream();
context.Response.Body = memoryStream;
await _next(context);
if (context.Response.StatusCode == StatusCodes.Status415UnsupportedMediaType)
{
var result = ApiResult.Fail("请求参数格式不正确", ResultCode.ValidationError);
var json = JsonSerializer.Serialize(result);
var bytes = Encoding.UTF8.GetBytes(json);
context.Response.Clear();
context.Response.StatusCode = StatusCodes.Status200OK; // 统一成200,和其他接口一致
context.Response.ContentType = "application/json; charset=utf-8";
context.Response.ContentLength = bytes.Length;
await context.Response.Body.WriteAsync(bytes);
await context.Response.Body.FlushAsync(originalBodyStream is null ? default : default);
}
else
{
// 非415的情况,把内存流内容原样写回真正的Response.Body
memoryStream.Seek(0, SeekOrigin.Begin);
await memoryStream.CopyToAsync(originalBodyStream);
}
context.Response.Body = originalBodyStream;
}
}
}
@@ -4,7 +4,7 @@ using System;
using System.Collections.Generic;
using System.Text;
namespace StoreHub.Framework.DependencyInjection
namespace MAX.Framework.DependencyInjection
{
public static class FreeSqlDB
{
@@ -0,0 +1,123 @@
//using MAX.Framework.Interfaces;
//using Microsoft.AspNetCore.Builder;
//using Microsoft.Extensions.Configuration;
//using Microsoft.Extensions.Configuration.Json;
//using Microsoft.Extensions.DependencyInjection;
//using System.Reflection;
//namespace MAX.Framework.DependencyInjection
//{
// /// <summary>
// /// 宿主(Program.cs)入口:模块两阶段装配 + 模块自己的配置文件。
// /// <code>
// /// var builder = WebApplication.CreateBuilder(args);
// /// builder.AddStoreHub(); // 阶段一:加载各模块配置文件 + 自动执行所有 IModule.AddModule
// ///
// /// var app = builder.Build();
// /// // ... 宿主自己的中间件、认证、端点 ...
// /// app.UseStoreHubModules(); // 阶段二:管道装配(自动执行所有 IModule.UseModule)
// /// app.Run();
// /// </code>
// /// </summary>
// public static class HostBuilderExtensions
// {
// /// <summary>
// /// 在 <see cref="WebApplicationBuilder"/> 上注册应用框架服务:
// /// <list type="number">
// /// <item>发现所有 <see cref="IModule"/>;</item>
// /// <item>把每个模块声明的 <see cref="IModule.ConfigurationFile"/> 并入宿主配置树(宿主 appsettings.json 不需要放模块的配置);</item>
// /// <item>再执行 <c>builder.Services.AddStoreHub(builder.Configuration, builder.Environment)</c>。</item>
// /// </list>
// /// </summary>
// public static WebApplicationBuilder AddStore(this WebApplicationBuilder builder)
// {
// IEnumerable<Assembly> assemblies = ServiceCollectionExtensions.GetApplicationAssemblies();
// // 同一个类可能同时实现 IStartup 与 IModule,这里缓存实例,保证后面两个阶段拿到的是同一个对象
// Dictionary<Type, object> instances = [];
// ModuleRegistry modules = ServiceCollectionExtensions.DiscoverModules(assemblies, instances);
// // 必须在跑 AddModule 之前并入,模块注册时才读得到自己的配置节
// foreach (IModule module in modules.Modules)
// {
// AddModuleConfigurationFile(builder.Configuration, module);
// }
// builder.Services.AddStoreHubCore(assemblies, modules, instances, builder.Configuration, builder.Environment);
// return builder;
// }
// /// <summary>
// /// 执行所有模块的管道阶段(<see cref="IModule.UseModule"/>):注册中间件、看板、Map 端点等。
// /// </summary>
// public static WebApplication UseStoreHubModules(this WebApplication app)
// {
// // 宿主没调用过 AddStoreHub() 时容器里没有注册表,直接返回即可
// ModuleRegistry? registry = app.Services.GetService<ModuleRegistry>();
// if (registry is null)
// {
// return app;
// }
// foreach (IModule module in registry.Modules)
// {
// try
// {
// module.UseModule(app);
// }
// catch (Exception ex)
// {
// throw new InvalidOperationException($"模块 {module.GetType().FullName} 的 UseModule 执行失败。", ex);
// }
// }
// return app;
// }
// /// <summary>
// /// 把模块自己的配置文件并进宿主配置:插在 appsettings*.json 之后、环境变量/命令行之前,
// /// 这样模块配置能覆盖宿主 appsettings.json,同时仍然允许用环境变量/命令行覆盖它。
// /// </summary>
// private static void AddModuleConfigurationFile(IConfigurationBuilder configuration, IModule module)
// {
// string? fileName = module.ConfigurationFile;
// if (string.IsNullOrWhiteSpace(fileName))
// {
// return;
// }
// string path = Path.IsPathRooted(fileName)
// ? fileName
// : Path.Combine(AppContext.BaseDirectory, fileName);
// JsonConfigurationSource source = new()
// {
// Path = path,
// Optional = true, // 文件不存在时不报错(模块没配就是没有)
// ReloadOnChange = true // 允许改配置不重启(与 appsettings.json 行为一致)
// };
// source.ResolveFileProvider();
// IList<IConfigurationSource> sources = configuration.Sources;
// int index = sources.Count;
// // 找到最后一个 appsettings*.json,插到它后面
// for (int i = sources.Count - 1; i >= 0; i--)
// {
// if (sources[i] is FileConfigurationSource file
// && Path.GetFileName(file.Path).StartsWith("appsettings", StringComparison.OrdinalIgnoreCase))
// {
// index = i + 1;
// break;
// }
// }
// sources.Insert(index, source);
// if (configuration is IConfigurationRoot root)
// {
// root.Reload();
// }
// }
// }
//}
@@ -1,15 +1,15 @@
using Asp.Versioning.OpenApi;
using Asp.Versioning.OpenApi;
using MAX.Framework.Security;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi;
using StoreHub.Framework.Security;
using System.Security.Claims;
using System.Text;
namespace StoreHub.Framework.DependencyInjection;
namespace MAX.Framework.DependencyInjection;
/// <summary>
/// JWT 认证服务注册入口(由宿主 Program.cs 调用)。
@@ -21,7 +21,7 @@ public static class JwtServiceCollectionExtensions
/// <list type="number">
/// <item>绑定 <c>Jwt</c> 配置节到 <see cref="JwtOptions"/>,并在启动时校验签名密钥长度;</item>
/// <item>注册 <see cref="ITokenService"/>(令牌生成/校验)与 <see cref="ICurrentUser"/>(当前用户访问器);</item>
/// <item>注册 <see cref="JwtBearerDefaults"/> 认证,认证失败/授权失败统一返回 <see cref="StoreHub.Framework.Commons.ApiResult{T}"/> 格式;</item>
/// <item>注册 <see cref="JwtBearerDefaults"/> 认证,认证失败/授权失败统一返回 <see cref="Dtos.ApiResult{T}"/> 格式;</item>
/// <item>注册 <see cref="IOnlineUserStore"/>(基于 <c>IMemoryCache</c> 的在线会话存储):单点登录、在线人员查询、退出销毁;</item>
/// <item>为 OpenAPI 文档声明 Bearer(JWT) 安全方案,并对标记了 [Authorize] 的接口声明需要携带令牌。</item>
/// </list>
@@ -68,12 +68,12 @@ public static class JwtServiceCollectionExtensions
{
IOnlineUserStore onlineUserStore = context.HttpContext.RequestServices.GetRequiredService<IOnlineUserStore>();
ClaimsPrincipal? principal = context.Principal;
string? userIdValue = principal?.FindFirst(JwtClaimTypes.UserId)?.Value;
string? userName = principal?.FindFirst(JwtClaimTypes.UserName)?.Value;
string? jti = principal?.FindFirst(JwtClaimTypes.Jti)?.Value;
if (!int.TryParse(userIdValue, out int userId)
if (string.IsNullOrWhiteSpace(userName)
|| string.IsNullOrWhiteSpace(jti)
|| !onlineUserStore.IsTokenActive(userId, jti))
|| !onlineUserStore.IsTokenActive(userName, jti))
{
context.Fail(new SecurityTokenException("登录已失效,请重新登录"));
}
@@ -0,0 +1,22 @@
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Web;
using System;
using System.Collections.Generic;
using System.Text;
namespace MAX.Framework.DependencyInjection
{
public static class LoggerExtensions
{
public static WebApplicationBuilder AddLogger(this WebApplicationBuilder builder)
{
builder.Logging.ClearProviders();
//builder.Logging.SetMinimumLevel(LogLevel.Information);
builder.Host.UseNLog();
return builder;
}
}
}
@@ -0,0 +1,227 @@
using MAX.Core.DependencyInjection;
using MAX.Core.Interfaces;
using MAX.Framework.Commons;
using MAX.Framework.Dtos;
using MAX.Framework.Interfaces;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Win32;
using System.Configuration;
using System.Diagnostics;
using System.Reflection;
namespace MAX.Framework.DependencyInjection
{
/// <summary>
/// IOC 注册入口(由宿主 Program.cs 调用)
/// </summary>
public static class ServiceCollectionExtensions
{
private static readonly Type[] DependencyMarkers =
[
typeof(ISingletonDependency),
typeof(IScopedDependency),
typeof(ITransientDependency),
];
/// <summary>
/// 添加框架注册
/// </summary>
public static IServiceCollection AddStore(this IHostApplicationBuilder host)
{
IEnumerable<Assembly> assemblies = GetApplicationAssemblies();
// 同一个类可能同时实现 IStartup 与 IModule,这里缓存实例,保证两个阶段拿到的是同一个对象
Dictionary<Type, object> instances = [];
return AddStoreCore(host, assemblies, instances);
}
/// <summary>
/// 注册应用服务的公共实现:宿主入口(<c>builder.AddStoreHub()</c>)与 <see cref="IServiceCollection"/> 入口共用。
/// </summary>
internal static IServiceCollection AddStoreCore(
IHostApplicationBuilder host,
IEnumerable<Assembly> assemblies,
IDictionary<Type, object> instances)
{
RegisterDependencyMarkers(host.Services, assemblies);
RunModules(host, assemblies, instances);
RunStartups(host.Services, assemblies, instances);
host.Services.AddControllers(options =>
{
options.Filters.Add<GlobalExceptionFilter>();
options.Filters.Add<UnifyResultFilter>();
}).ConfigureApiBehaviorOptions(options =>
{
options.InvalidModelStateResponseFactory = context =>
{
// 取出所有校验错误信息,拼成一个字符串(或者只取第一个)
var errors = context.ModelState
.Where(e => e.Value?.Errors.Count > 0)
.SelectMany(e => e.Value!.Errors.Select(err => err.ErrorMessage))
.ToList();
var msg = string.Join("; ", errors);
var result = ApiResult.Fail(msg, ResultCode.ValidationError);
return new ObjectResult(result)
{
StatusCode = 200 // 和其他接口保持一致,用Code表达失败,而不是HTTP 400
};
};
});
return host.Services;
}
/// <summary>
/// 自动注册标记接口(ISingletonDependency / IScopedDependency / ITransientDependency)的实现类型
/// </summary>
private static void RegisterDependencyMarkers(IServiceCollection services, IEnumerable<Assembly> assemblies)
{
foreach (Type type in GetConcreteTypes(assemblies))
{
Debug.WriteLine(type.Namespace);
Type? marker = DependencyMarkers.FirstOrDefault(m => m.IsAssignableFrom(type));
if (marker is null)
{
continue;
}
ServiceLifetime lifetime = marker == typeof(ISingletonDependency) ? ServiceLifetime.Singleton
: marker == typeof(IScopedDependency) ? ServiceLifetime.Scoped
: ServiceLifetime.Transient;
// 注册为自身
services.Add(new ServiceDescriptor(type, type, lifetime));
// 注册为实现的接口(排除标记接口与系统接口)
foreach (Type iface in type.GetInterfaces())
{
if (DependencyMarkers.Contains(iface) || IsSystemInterface(iface))
{
continue;
}
services.Add(new ServiceDescriptor(iface, type, lifetime));
}
}
}
private static IEnumerable<IStartup> Startups = [];
/// <summary>
/// 发现所有 <see cref="IStartup"/> 实现,按 <see cref="IStartup.Priority"/> 降序执行
/// </summary>
private static void RunStartups(IServiceCollection services, IEnumerable<Assembly> assemblies, IDictionary<Type, object> instances)
{
IServiceRegistrar registrar = new ServiceRegistrarProxy(services);
Startups = CreateInstances<IStartup>(assemblies, instances).OrderByDescending(s => s.Priority);
foreach (IStartup startup in Startups)
{
startup.Initialize();
startup.Register(registrar);
}
}
private static IEnumerable<IModule> Modules = [];
/// <summary>
/// 执行所有模块的服务注册阶段(<see cref="IModule.AddModule"/>)
/// </summary>
private static void RunModules(IHostApplicationBuilder host, IEnumerable<Assembly> assemblies, IDictionary<Type, object> instances)
{
Modules = CreateInstances<IModule>(assemblies, instances).OrderByDescending(s => s.Priority);
foreach (IModule module in Modules)
{
try
{
module.AddModule(host);
}
catch (Exception ex)
{
// 带上模块名,避免只看到一个没有上下文的异常
throw new InvalidOperationException($"模块 {module.GetType().FullName} 的 AddModule 执行失败。", ex);
}
}
}
/// <summary>
/// 反射创建(或复用)所有实现 <typeparamref name="T"/> 的具体类型实例
/// </summary>
private static IEnumerable<T> CreateInstances<T>(IEnumerable<Assembly> assemblies, IDictionary<Type, object> instances) where T : class
{
foreach (Type type in GetConcreteTypes(assemblies).Where(t => typeof(T).IsAssignableFrom(t)))
{
if (!instances.TryGetValue(type, out object? instance))
{
instance = Activator.CreateInstance(type, true)
?? throw new InvalidOperationException($"无法创建 {type.FullName} 的实例(需要有参数量为 0 的构造函数)。");
instances[type] = instance;
}
yield return (T)instance;
}
}
private static IEnumerable<Type> GetConcreteTypes(IEnumerable<Assembly> assemblies)
{
return assemblies
.SelectMany(SafeGetTypes)
.Where(t => t.IsClass && !t.IsAbstract && !t.IsGenericTypeDefinition);
}
private static IEnumerable<Type> SafeGetTypes(Assembly assembly)
{
try
{
return assembly.GetTypes();
}
catch (ReflectionTypeLoadException ex)
{
return ex.Types.OfType<Type>();
}
}
/// <summary>
/// 应用程序集(模块、Startup 都从这里发现)
/// </summary>
internal static IEnumerable<Assembly> GetApplicationAssemblies()
{
// 使用 AppTypeFinder:扫描应用输出目录 + 已加载程序集,
return StoreAppTypeFinder.Current.GetAssemblies();
}
private static bool IsSystemInterface(Type type)
{
return type.Namespace is null
|| type.Namespace.StartsWith("System", StringComparison.Ordinal)
|| type.Namespace.StartsWith("Microsoft", StringComparison.Ordinal);
}
public static IApplicationBuilder UseStore(this IApplicationBuilder app)
{
foreach (IStartup startup in Startups)
{
startup.Start((app as IHost).Services);
}
foreach (IModule module in Modules)
{
module.UseModule(app);
}
return app;
}
}
}
@@ -1,7 +1,7 @@
using MAX.Core.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
namespace StoreHub.Framework.DependencyInjection
namespace MAX.Framework.DependencyInjection
{
/// <summary>
/// 将 <see cref="IServiceRegistrar"/> 适配到 Microsoft.Extensions.DependencyInjection
@@ -1,18 +1,18 @@
using MAX.Core.Reflections;
namespace StoreHub.Framework.DependencyInjection
namespace MAX.Framework.DependencyInjection
{
/// <summary>
/// 本应用的类型查找器:在 AppTypeFinder 默认前缀(MAX. / Nexus.)之外,
/// 增加 StoreHub、KJD 前缀,用于发现宿主和各业务模块的程序集。
/// </summary>
internal sealed class StoreHubAppTypeFinder : AppTypeFinder
internal sealed class StoreAppTypeFinder : AppTypeFinder
{
public static StoreHubAppTypeFinder Current { get; } = new();
public static StoreAppTypeFinder Current { get; } = new();
protected override List<string> AvailablePrefix()
{
return ["StoreHub"];
return ["Store"];
}
}
}
+69
View File
@@ -0,0 +1,69 @@
using MAX.Framework.Commons;
using static System.Runtime.InteropServices.JavaScript.JSType;
namespace MAX.Framework.Dtos
{
public static class ResultCode
{
public const int Success = 200;
public const int Fail = 500;
public const int Unauthorized = 401;
public const int Forbidden = 403;
public const int NotFound = 404;
/// <summary>
/// 参数校验失败
/// </summary>
public const int ValidationError = 1001;
/// <summary>
/// 业务逻辑异常
/// </summary>
public const int BusinessError = 2001;
/// <summary>
/// 服务器内部错误
/// </summary>
public const int ServerError = 5000;
}
/// <summary>
/// 非泛型基类,用于统一处理
/// </summary>
public abstract class ApiResultBase
{
/// <summary>业务状态码</summary>
public int Code { get; set; } = ResultCode.Success;
/// <summary>提示信息</summary>
public string? Msg { get; set; }
/// <summary>请求是否成功</summary>
public bool Success => Code == ResultCode.Success;
}
/// <summary>
/// 泛型响应
/// </summary>
public class ApiResult<T> : ApiResultBase
{
public T? Data { get; set; }
public static ApiResult<T> Success(T data, string msg = "操作成功")
=> new ApiResult<T> { Code = ResultCode.Success, Data = data, Msg = msg };
public static ApiResult<T> Fail(string msg = "操作失败", int code = ResultCode.Fail, T? data = default)
=> new ApiResult<T> { Code = code, Msg = msg, Data = data };
}
/// <summary>
/// 响应
/// </summary>
public class ApiResult : ApiResult<object>
{
public static ApiResult Success(string msg = "操作成功")
=> new ApiResult { Code = ResultCode.Success, Msg = msg };
public static ApiResult Fail(string msg = "操作失败", int code = ResultCode.Fail)
=> new ApiResult { Code = code, Msg = msg };
}
}
@@ -4,7 +4,7 @@ using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
namespace StoreHub.Framework.Helpers;
namespace MAX.Framework.Helpers;
public static class ObjectHelper
{
@@ -3,7 +3,7 @@ using System;
using System.Diagnostics;
using System.Text;
namespace StoreHub.Framework.Helpers;
namespace MAX.Framework.Helpers;
public class WinCmdHelper
{
+22
View File
@@ -0,0 +1,22 @@
using MAX.Core.Interfaces;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Hosting;
namespace MAX.Framework.Interfaces
{
/// <summary>
/// 模块实例由反射创建,因此实现类必须有无参构造函数。
/// </summary>
public interface IModule : IPriority
{
/// <summary>
/// 添加Module
/// </summary>
void AddModule(IHostApplicationBuilder host);
/// <summary>
/// 管道装配阶段
/// </summary>
void UseModule(IApplicationBuilder app);
}
}
+138
View File
@@ -0,0 +1,138 @@
//using MAX.Core.Infrastructure;
//using MAX.Core.Logger;
//using NLog;
//using System;
//using LLogLevel = MAX.Core.Logger.LogLevel;
//using NLogLevel = NLog.LogLevel;
//namespace MAX.Framework.Logger;
//public class NLogger : SingleInstance<NLogger>, ILoggerFacade
//{
// private readonly ILogger _log;
// private NLogger()
// {
// _log = LogManager.GetLogger("GlobalLogger");
// }
// public bool IsDebugEnabled { get; private set; } = true;
// public void Debug(Exception ex, string message)
// {
// Execute(NLogLevel.Debug, ex, message);
// }
// public void Debug(string message)
// {
// Execute(NLogLevel.Debug, message);
// }
// public void Error(Exception ex)
// {
// Execute(NLogLevel.Error, ex);
// }
// public void Error(Exception ex, string message)
// {
// Execute(NLogLevel.Error, ex, message);
// }
// public void Error(string message)
// {
// Execute(NLogLevel.Error, message);
// }
// public void Fatal(Exception ex, string message)
// {
// Execute(NLogLevel.Fatal, ex, message);
// }
// public void Fatal(string message)
// {
// Execute(NLogLevel.Fatal, message);
// }
// public void Info(Exception ex, string message)
// {
// Execute(NLogLevel.Info, ex, message);
// }
// public void Info(string message)
// {
// Execute(NLogLevel.Info, message);
// }
// public void Warn(Exception ex, string message)
// {
// Execute(NLogLevel.Warn, ex, message);
// }
// public void Warn(string message)
// {
// Execute(NLogLevel.Warn, message);
// }
// public void Log(string message, LLogLevel level)
// {
// NLogLevel lv = NLogLevel.Info;
// switch (level)
// {
// case LLogLevel.Trace:
// lv = NLogLevel.Trace;
// break;
// case LLogLevel.Debug:
// lv = NLogLevel.Debug;
// break;
// case LLogLevel.Info:
// lv = NLogLevel.Info;
// break;
// case LLogLevel.Warn:
// lv = NLogLevel.Warn;
// break;
// case LLogLevel.Error:
// lv = NLogLevel.Error;
// break;
// case LLogLevel.Fatal:
// lv = NLogLevel.Fatal;
// break;
// case LLogLevel.None:
// lv = NLogLevel.Off;
// break;
// }
// Execute(lv, message);
// }
// /// <summary>
// /// 是否启用
// /// </summary>
// private bool Enabled(NLogLevel level)
// {
// if (level > NLogLevel.Debug)
// {
// return true;
// }
// return IsDebugEnabled;
// }
// /// <summary>
// /// 执行
// /// </summary>
// private void Execute(NLogLevel level, Exception ex, string message = "")
// {
// if (Enabled(level))
// {
// _log.Log(level, ex, message, null);
// }
// }
// /// <summary>
// /// 执行
// /// </summary>
// private void Execute(NLogLevel level, string message)
// {
// if (Enabled(level))
// {
// _log.Log(level, message);
// }
// }
//}
@@ -8,10 +8,6 @@
<FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Core\MAX.Core\MAX.Core.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Asp.Versioning.Mvc.ApiExplorer" Version="10.2.1" />
<PackageReference Include="Asp.Versioning.OpenApi" Version="10.2.1" />
@@ -19,8 +15,16 @@
<PackageReference Include="FreeSql.Provider.MySql" Version="3.5.311" />
<PackageReference Include="FreeSql.Repository" Version="3.5.311" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.10" />
<PackageReference Include="NLog" Version="6.1.4" />
<PackageReference Include="NLog.Web.AspNetCore" Version="6.2.0" />
<PackageReference Include="Riok.Mapperly" Version="4.3.1" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\MAX.Core\MAX.Core.csproj" />
</ItemGroup>
<ItemGroup>
<Folder Include="Models\" />
</ItemGroup>
</Project>
@@ -1,8 +1,8 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http;
using System.Globalization;
using System.Security.Claims;
namespace StoreHub.Framework.Security;
namespace MAX.Framework.Security;
/// <summary>
/// 从 <see cref="IHttpContextAccessor"/> 读取当前请求认证票据的默认实现。
@@ -24,16 +24,6 @@ public class CurrentUser : ICurrentUser
/// <inheritdoc />
public bool IsAuthenticated => Principal?.Identity?.IsAuthenticated == true;
/// <inheritdoc />
public int? Id
{
get
{
string? value = GetClaimValue(JwtClaimTypes.UserId);
return int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int id) ? id : null;
}
}
/// <inheritdoc />
public string? UserName => GetClaimValue(JwtClaimTypes.UserName);
@@ -1,6 +1,6 @@
using System.Security.Claims;
using System.Security.Claims;
namespace StoreHub.Framework.Security;
namespace MAX.Framework.Security;
/// <summary>
/// 当前登录用户访问器:从当前请求的认证票据中读取用户信息。
@@ -12,11 +12,6 @@ public interface ICurrentUser
/// </summary>
bool IsAuthenticated { get; }
/// <summary>
/// 当前用户ID(未登录为 null)
/// </summary>
int? Id { get; }
/// <summary>
/// 当前登录账户名(未登录为 null)
/// </summary>
@@ -1,4 +1,4 @@
namespace StoreHub.Framework.Security;
namespace MAX.Framework.Security;
/// <summary>
/// 在线用户会话存储:基于 <see cref="Microsoft.Extensions.Caching.Memory.IMemoryCache"/> 的进程内实现,
@@ -12,14 +12,14 @@ public interface IOnlineUserStore
void SignIn(OnlineUserInfo info);
/// <summary>
/// 判断指定用户、指定令牌会话是否仍然有效(未被退出、未被新登录顶替)。
/// 判断指定登录账户、指定令牌会话是否仍然有效(未被退出、未被新登录顶替)。
/// </summary>
bool IsTokenActive(int userId, string jti);
bool IsTokenActive(string userName, string jti);
/// <summary>
/// 退出登录:销毁该用户的在线会话,令牌立即失效。
/// 退出登录:销毁该账户的在线会话,令牌立即失效。
/// </summary>
void SignOut(int userId);
void SignOut(string userName);
/// <summary>
/// 获取当前在线人员列表。
@@ -1,6 +1,6 @@
using System.Security.Claims;
namespace StoreHub.Framework.Security;
namespace MAX.Framework.Security;
/// <summary>
/// 令牌生成结果
@@ -18,9 +18,9 @@ public class TokenResult
public string Token { get; set; } = string.Empty;
/// <summary>
/// 过期时间(本地时间)
/// 有效时间(分钟)
/// </summary>
public DateTime ExpiresAt { get; set; }
public uint ExpiresInMinutes { get; set; }
}
/// <summary>
@@ -1,10 +1,10 @@
using Microsoft.AspNetCore.Authentication.JwtBearer;
using MAX.Framework.Dtos;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Http;
using StoreHub.Framework.Commons;
using System.Text;
using System.Text.Json;
namespace StoreHub.Framework.Security;
namespace MAX.Framework.Security;
/// <summary>
/// JwtBearer 认证失败/授权失败时,统一返回 <see cref="ApiResult{T}"/> 格式的 JSON 响应。
@@ -38,7 +38,7 @@ internal static class JwtBearerResponseHandler
httpContext.Response.StatusCode = statusCode;
httpContext.Response.ContentType = "application/json; charset=utf-8";
string body = JsonSerializer.Serialize(ApiResult.Error(message, statusCode), JsonOptions);
string body = JsonSerializer.Serialize(ApiResult.Fail(message, statusCode), JsonOptions);
await httpContext.Response.WriteAsync(body, Encoding.UTF8);
}
}
@@ -1,14 +1,11 @@
namespace StoreHub.Framework.Security;
namespace MAX.Framework.Security;
/// <summary>
/// JWT 自定义声明类型常量。
/// </summary>
public static class JwtClaimTypes
{
/// <summary>用户ID</summary>
public const string UserId = "uid";
/// <summary>登录账户</summary>
/// <summary>登录账户(唯一)</summary>
public const string UserName = "user_name";
/// <summary>用户昵称</summary>
@@ -1,7 +1,7 @@
using Microsoft.IdentityModel.Tokens;
using System.Text;
namespace StoreHub.Framework.Security;
namespace MAX.Framework.Security;
/// <summary>
/// JWT 配置选项,默认绑定配置节 <c>Jwt</c>。
@@ -1,14 +1,11 @@
namespace StoreHub.Framework.Security;
namespace MAX.Framework.Security;
/// <summary>
/// 在线用户会话信息(单点登录:同一用户仅保留一个有效会话)。
/// </summary>
public class OnlineUserInfo
{
/// <summary>用户ID</summary>
public int UserId { get; set; }
/// <summary>登录账户</summary>
/// <summary>登录账户(唯一,作为会话键)</summary>
public string UserName { get; set; } = string.Empty;
/// <summary>用户昵称</summary>
@@ -1,7 +1,7 @@
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Caching.Memory;
using System.Collections.Concurrent;
namespace StoreHub.Framework.Security;
namespace MAX.Framework.Security;
/// <summary>
/// 基于 <see cref="IMemoryCache"/> 的在线用户会话存储。
@@ -11,7 +11,7 @@ public class OnlineUserStore : IOnlineUserStore
private const string CacheKeyPrefix = "online:user:";
private readonly IMemoryCache _cache;
// 在线人员索引:IMemoryCache 不提供公共枚举 API,这里用字典维护便于查询在线列表
private readonly ConcurrentDictionary<int, OnlineUserInfo> _onlineIndex = new();
private readonly ConcurrentDictionary<string, OnlineUserInfo> _onlineIndex = new(StringComparer.Ordinal);
public OnlineUserStore(IMemoryCache cache)
{
@@ -23,33 +23,33 @@ public class OnlineUserStore : IOnlineUserStore
{
ArgumentNullException.ThrowIfNull(info);
// 以 userId 为键覆盖写入:旧会话(jti)被顶替,实现单点登录
_cache.Set(GetKey(info.UserId), info, new MemoryCacheEntryOptions
// 以登录账户为键覆盖写入:旧会话(jti)被顶替,实现单点登录
_cache.Set(GetKey(info.UserName), info, new MemoryCacheEntryOptions
{
// 缓存条目与令牌同时过期,过期后自动失效
AbsoluteExpiration = info.ExpiresAt,
});
_onlineIndex[info.UserId] = info;
_onlineIndex[info.UserName] = info;
}
/// <inheritdoc />
public bool IsTokenActive(int userId, string jti)
public bool IsTokenActive(string userName, string jti)
{
if (string.IsNullOrWhiteSpace(jti))
if (string.IsNullOrWhiteSpace(userName) || string.IsNullOrWhiteSpace(jti))
{
return false;
}
return _cache.TryGetValue(GetKey(userId), out OnlineUserInfo? info)
return _cache.TryGetValue(GetKey(userName), out OnlineUserInfo? info)
&& info is not null
&& string.Equals(info.Jti, jti, StringComparison.Ordinal);
}
/// <inheritdoc />
public void SignOut(int userId)
public void SignOut(string userName)
{
_cache.Remove(GetKey(userId));
_onlineIndex.TryRemove(userId, out _);
_cache.Remove(GetKey(userName));
_onlineIndex.TryRemove(userName, out _);
}
/// <inheritdoc />
@@ -57,7 +57,7 @@ public class OnlineUserStore : IOnlineUserStore
{
DateTime now = DateTime.Now;
List<OnlineUserInfo> result = [];
foreach (KeyValuePair<int, OnlineUserInfo> pair in _onlineIndex)
foreach (KeyValuePair<string, OnlineUserInfo> pair in _onlineIndex)
{
if (pair.Value.ExpiresAt > now)
{
@@ -75,6 +75,6 @@ public class OnlineUserStore : IOnlineUserStore
/// <inheritdoc />
public int Count => GetOnlineUsers().Count;
private static string GetKey(int userId) => $"{CacheKeyPrefix}{userId}";
private static string GetKey(string userName) => $"{CacheKeyPrefix}{userName}";
}
@@ -1,10 +1,10 @@
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.JsonWebTokens;
using Microsoft.IdentityModel.Tokens;
using System.Security.Claims;
using System.Text;
namespace StoreHub.Framework.Security;
namespace MAX.Framework.Security;
/// <summary>
/// 基于 <see cref="JwtOptions"/> 的 JWT 令牌服务。
@@ -50,7 +50,7 @@ public class TokenService : ITokenService
return new TokenResult
{
Token = token,
ExpiresAt = expires,
ExpiresInMinutes = (uint)_options.ExpiresMinutes,
};
}
@@ -74,9 +74,9 @@ public class TokenService : ITokenService
ClaimsPrincipal principal = new(result.ClaimsIdentity);
// 单点登录校验:会话必须仍然有效(未被退出、未被新登录顶替)
string? userIdValue = principal.FindFirst(JwtClaimTypes.UserId)?.Value;
string? userName = principal.FindFirst(JwtClaimTypes.UserName)?.Value;
string? jti = principal.FindFirst(JwtClaimTypes.Jti)?.Value;
if (!int.TryParse(userIdValue, out int userId) || string.IsNullOrWhiteSpace(jti) || !_onlineUserStore.IsTokenActive(userId, jti))
if (string.IsNullOrWhiteSpace(userName) || string.IsNullOrWhiteSpace(jti) || !_onlineUserStore.IsTokenActive(userName, jti))
{
return null;
}
@@ -94,16 +94,15 @@ public class TokenService : ITokenService
/// </summary>
private void RegisterSession(IEnumerable<Claim> claims, string jti, DateTime loginTime, DateTime expiresAt)
{
string? userIdValue = claims.FirstOrDefault(c => c.Type == JwtClaimTypes.UserId)?.Value;
if (!int.TryParse(userIdValue, out int userId))
string? userName = claims.FirstOrDefault(c => c.Type == JwtClaimTypes.UserName)?.Value;
if (string.IsNullOrWhiteSpace(userName))
{
return; // 未携带用户ID的令牌不纳入在线会话管理
return; // 未携带登录账户的令牌不纳入在线会话管理
}
_onlineUserStore.SignIn(new OnlineUserInfo
{
UserId = userId,
UserName = claims.FirstOrDefault(c => c.Type == JwtClaimTypes.UserName)?.Value ?? string.Empty,
UserName = userName,
NickName = claims.FirstOrDefault(c => c.Type == JwtClaimTypes.NickName)?.Value ?? string.Empty,
Jti = jti,
LoginTime = loginTime,
+29
View File
@@ -0,0 +1,29 @@
using FreeSql;
using MAX.Core.DependencyInjection;
using MAX.Core.Interfaces;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace MAX.Framework
{
public class Startup : IStartup
{
public int Priority => IntPriority.Highest;
public void Initialize()
{
}
public void Register(IServiceRegistrar registrar)
{
}
public void Start(IServiceProvider serviceProvider)
{
}
}
}
+125
View File
@@ -0,0 +1,125 @@
using Hangfire;
using Hangfire.MySql;
using HangfireBasicAuthenticationFilter;
using MAX.Core.Interfaces;
using MAX.Framework.Interfaces;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using MySql.Data.MySqlClient;
using Store.Modules.CloudProduct.Services;
namespace Store.Modules.CloudProduct
{
/// <summary>
/// CloudProduct 模块的模块化入口(<see cref="IModule"/>):Hangfire 后台任务(商品分词同步)+ Hangfire 看板。
/// 与 <see cref="Startup"/>(只做 IStartup 的 Initialize/Register)分开,是因为模块注册需要配置和 app:
/// <list type="bullet">
/// <item><c>builder.AddStoreHub()</c> 执行 <see cref="AddModule"/>(注册 Hangfire 服务,此时只能拿到容器和配置);</item>
/// <item><c>app.UseStoreHubModules()</c> 执行 <see cref="UseModule"/>(挂看板中间件 + 注册定时任务,此时才有 app)。</item>
/// </list>
/// </summary>
public class CloudProductModule : IModule
{
/// <summary>
/// 本模块自己的配置文件(源码里是 Models/CloudProduct/appsettings.json,
/// 构建时复制到宿主输出目录并改名成这个名字,避免与宿主的 appsettings.json 冲突)
/// </summary>
public const string ConfigurationFileName = "appsettings.CloudProduct.json";
public int Priority => IntPriority.Normal;
/// <summary>
/// 服务注册阶段(builder.Build() 之前):这里只能拿到容器和配置,碰不到 app
/// </summary>
public void AddModule(IHostApplicationBuilder host)
{
IServiceCollection services = host.Services;
IConfigurationManager configuration = host.Configuration;
if (!string.IsNullOrWhiteSpace(ConfigurationFileName))
{
string path = Path.IsPathRooted(ConfigurationFileName)? ConfigurationFileName: Path.Combine(AppContext.BaseDirectory, ConfigurationFileName);
configuration.AddJsonFile(path, optional: false, reloadOnChange: true);
}
//// 本模块的配置节(Search / RawData / Indexing / Delete)都在模块自己的配置文件里,
//// 关键项缺失直接报错,避免 OpenSearch 地址为空、原始数据写到意外目录之类的隐性故障
RequireConfiguration(configuration, "Search:Url");
//RequireConfiguration(configuration, "Search:IndexName");
//RequireConfiguration(configuration, "RawData:Path");
// ===== Hangfire 后台定时任务(商品分词同步) =====
var hangfireConnection = configuration.GetConnectionString("DefaultConnection")
?? throw new InvalidOperationException("缺少配置 ConnectionStrings:DefaultConnection,CloudProduct 模块的 Hangfire 无法启动。");
// AllowUserVariables=true:Hangfire.MySqlStorage 的建表/查询语句依赖用户变量
var connectionStringBuilder = new MySqlConnectionStringBuilder(hangfireConnection)
{
AllowUserVariables = true
};
services.AddHangfire(config => config
.SetDataCompatibilityLevel(CompatibilityLevel.Version_180)
.UseSimpleAssemblyNameTypeSerializer()
.UseRecommendedSerializerSettings()
.UseStorage(new MySqlStorage(connectionStringBuilder.ConnectionString, new MySqlStorageOptions() { TablesPrefix = "Hangfire_" })));
services.AddHangfireServer();
services.AddTransient<GoodsIndexJob>();
}
/// <summary>
/// 管道装配阶段(builder.Build() 之后、app.Run() 之前):这里可以挂中间件、解析容器里的服务
/// </summary>
public void UseModule(IApplicationBuilder app)
{
try
{
var Configuration = app.ApplicationServices.GetService<IConfiguration>()!;
// Hangfire 后台任务看板(默认地址 /hangfire)
app.UseHangfireDashboard("/hangfire", new DashboardOptions
{
Authorization = new[]
{
new HangfireCustomBasicAuthenticationFilter(){
User = Configuration.GetValue<string>("Hangfire:Dashboard:User") ?? "admin",
Pass = Configuration.GetValue<string>("Hangfire:Dashboard:Pass") ?? "1234560"
}
}
});
// 注册定时任务:把未同步(IndexStatus=0)的商品写入 OpenSearch 分词索引
var cron = Configuration.GetValue<string>("Indexing:Cron") ?? "*/5 * * * *";
// 用容器里的 IRecurringJobManager,而不是静态 RecurringJob:
// AddHangfire 只把 JobStorage 注册进容器(没有设置 JobStorage.Current),静态 API 在 Build() 之后调用会直接抛异常。
app.ApplicationServices.GetRequiredService<IRecurringJobManager>().AddOrUpdate<GoodsIndexJob>(
"goods-index-pending",
job => job.ProcessPendingAsync(),
cron);
}
catch (Exception ex)
{
// 数据库不可用/表未初始化时避免阻断应用启动(看板与定时任务都会连库),恢复后重启即可重新装配
Console.WriteLine("[Hangfire] 看板/定时任务装配失败: " + ex.Message);
}
}
/// <summary>
/// 校验模块配置项存在(值来自模块自己的 <see cref="ConfigurationFileName"/>)
/// </summary>
private static void RequireConfiguration(IConfiguration configuration, string key)
{
if (string.IsNullOrWhiteSpace(configuration.GetValue<string>(key)))
{
throw new InvalidOperationException($"缺少配置 {key},请检查模块配置文件 {ConfigurationFileName}。");
}
}
}
}
@@ -0,0 +1,404 @@
using Asp.Versioning;
using MAX.Framework.Commons;
using MAX.Framework.Dtos;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Store.Framework.Base;
using Store.Modules.CloudProduct.Dtos;
using Store.Modules.CloudProduct.Entities;
using Store.Modules.CloudProduct.ImportConverters;
using Store.Modules.CloudProduct.Services;
using System.Text.Json.Nodes;
namespace Store.Modules.CloudProduct.Controllers
{
[ApiVersionNeutral]
[Route("/CloudGoods/[action]")]
public class GoodsController : AppControllerBase
{
private readonly IGoodsService _goodsService;
private readonly IOpenSearchService _searchService;
private readonly IRawDataStorage _rawDataStorage;
private readonly GoodsIndexJob _goodsIndexJob;
public GoodsController(IGoodsService goodsService, IOpenSearchService searchService, IRawDataStorage rawDataStorage, GoodsIndexJob goodsIndexJob)
{
_goodsService = goodsService;
_searchService = searchService;
_rawDataStorage = rawDataStorage;
_goodsIndexJob = goodsIndexJob;
}
[HttpGet]
public async Task<string> Time()
{
return DateTime.Now.ToLongDateString();
}
[HttpGet]
public async Task Job()
{
await _goodsIndexJob.ProcessPendingAsync();
}
/// <summary>
/// 搜索
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
[HttpPost]
public async Task<PageData<GoodsEntity>> SearchGoods(GoodsSearchRequest request)
{
// 1. 参数基础校验
if (request == null)
{
throw new AppException("请求参数不能为空", ResultCode.ValidationError);
}
// 2. 分页参数校验
if (request.PageIndex < 1)
{
throw new AppException("页码必须大于0", ResultCode.ValidationError);
}
if (request.PageSize < 1 || request.PageSize > 2000)
{
throw new AppException("每页数量必须在1-2000之间", ResultCode.ValidationError);
}
// 3. 价格区间校验
if (request.MinPrice.HasValue && request.MinPrice < 0)
{
throw new AppException("最低价格不能小于0", ResultCode.ValidationError);
}
if (request.MaxPrice.HasValue && request.MaxPrice < 0)
{
throw new AppException("最高价格不能小于0", ResultCode.ValidationError);
}
if (request.MinPrice.HasValue && request.MaxPrice.HasValue && request.MinPrice > request.MaxPrice)
{
throw new AppException("最低价格不能大于最高价格", ResultCode.ValidationError);
}
// 4. 销量区间校验
if (request.MinSoldQuantity.HasValue && request.MinSoldQuantity < 0)
{
throw new AppException("最低销量不能小于0", ResultCode.ValidationError);
}
if (request.MaxSoldQuantity.HasValue && request.MaxSoldQuantity < 0)
{
throw new AppException("最高销量不能小于0", ResultCode.ValidationError);
}
if (request.MinSoldQuantity.HasValue && request.MaxSoldQuantity.HasValue &&
request.MinSoldQuantity > request.MaxSoldQuantity)
{
throw new AppException("最低销量不能大于最高销量", ResultCode.ValidationError);
}
// 5. 类目层级校验
if (request.CatId2.HasValue && !request.CatId1.HasValue)
{
throw new AppException("选择二级类目时必须先选择一级类目", ResultCode.ValidationError);
}
if (request.CatId3.HasValue && !request.CatId2.HasValue)
{
throw new AppException("选择三级类目时必须先选择二级类目", ResultCode.ValidationError);
}
if (request.CatId4.HasValue && !request.CatId3.HasValue)
{
throw new AppException("选择四级类目时必须先选择三级类目", ResultCode.ValidationError);
}
// 6. 平台校验
if (request.Platform.HasValue && request.Platform < 0)
{
throw new AppException("平台类型无效", ResultCode.ValidationError);
}
// 10. 至少有一个搜索条件
if (string.IsNullOrWhiteSpace(request.Title) &&
!request.MinPrice.HasValue && !request.MaxPrice.HasValue &&
!request.CatId1.HasValue && !request.CatId2.HasValue &&
!request.CatId3.HasValue && !request.CatId4.HasValue &&
!request.MinSoldQuantity.HasValue && !request.MaxSoldQuantity.HasValue &&
!request.Platform.HasValue)
{
throw new AppException("请至少提供一个搜索条件", ResultCode.ValidationError);
}
var result = await _goodsService.SearchGoodsAsync(request);
return new PageData<GoodsEntity>
{
List = result.List,
Total = result.Total,
PageSize = request.PageSize,
PageIndex = request.PageIndex,
};
}
/// <summary>
/// 分词搜索,直接返回索引中的商品摘要(路由保持 SearchGoodsToIds 不变)
/// </summary>
[HttpGet]
[ActionName("SearchGoodsToIds")]
public async Task<PageData<GoodsSearchDocument>> SearchGoodsSummary(string keyword, int pageindex = 1, int pagesize = 20)
{
if (string.IsNullOrWhiteSpace(keyword))
{
throw new AppException("填写关键字", ResultCode.ValidationError);
}
var result = await _searchService.SearchByTitleAsync(new GoodsSearchRequest
{
Title = keyword,
PageIndex = pageindex,
PageSize = pagesize,
});
return new PageData<GoodsSearchDocument>
{
PageIndex = pageindex,
PageSize = pagesize,
List = result.Documents,
Total = result.Total,
};
}
/// <summary>
/// 导入测试数据:读取 ImportConverters/data.txt 并走完整解析 + 入库 + 分词流程。
/// </summary>
[HttpGet]
public async Task<GoodsImportResult> ImportTestData()
{
var filePath = GetDataFilePath();
if (!System.IO.File.Exists(filePath))
{
throw new AppException($"找不到测试数据文件: {filePath}", ResultCode.NotFound);
}
var content = await System.IO.File.ReadAllTextAsync(filePath);
var goods = GoodsConverterFactory.ConvertContent(content);
if (goods == null)
{
throw new AppException("未找到匹配的转换器,无法解析测试数据");
}
return await _goodsService.ImportGoodsAsync(new[]
{
new GoodsImportItem { Goods = goods, RawData = content }
});
}
/// <summary>
/// 导入接口:接收客户端批量上传的 JSON 文件,解析后入库并写入分词索引。
/// </summary>
[HttpPost]
public async Task<GoodsImportResult> ImportFiles([FromForm] List<IFormFile> files)
{
if (files == null || files.Count == 0)
{
throw new AppException("请选择要导入的 JSON 文件", ResultCode.ValidationError);
}
var items = new List<GoodsImportItem>();
var parseErrors = new List<string>();
foreach (var file in files)
{
if (file == null || file.Length == 0)
{
continue;
}
try
{
using var reader = new StreamReader(file.OpenReadStream());
var content = await reader.ReadToEndAsync();
var goods = GoodsConverterFactory.ConvertContent(content);
if (goods == null)
{
parseErrors.Add($"{file.FileName}: 未找到匹配的转换器");
}
else
{
items.Add(new GoodsImportItem { Goods = goods, RawData = content });
}
}
catch (Exception ex)
{
parseErrors.Add($"{file.FileName}: {ex.Message}");
}
}
var result = await _goodsService.ImportGoodsAsync(items);
result.FailedCount += parseErrors.Count;
result.Errors.InsertRange(0, parseErrors);
return result;
}
/// <summary>
/// 查询 OpenSearch 状态。
/// </summary>
[HttpGet]
public async Task<OpenSearchStatusDto> GetOpenSearchStatus()
{
return await _searchService.GetStatusAsync();
}
/// <summary>
/// 检查搜索索引是否存在。
/// </summary>
[HttpGet]
public async Task<bool> IndexExists()
{
return await _searchService.IndexExistsAsync();
}
/// <summary>
/// 检查索引映射(分析器)是否符合当前服务要求。
/// </summary>
[HttpGet]
public async Task<bool> IndexMappingHealthy()
{
return await _searchService.IsIndexMappingHealthyAsync();
}
/// <summary>
/// 创建搜索索引(含 IK 分词映射,已存在且映射正常时跳过)。
/// </summary>
[HttpPost]
public async Task<bool> CreateIndex()
{
return await _searchService.CreateIndexAsync();
}
/// <summary>
/// 删除搜索索引。
/// </summary>
[HttpPost]
public async Task DeleteIndex()
{
await _searchService.DeleteIndexAsync();
}
/// <summary>
/// 手动刷新搜索索引,使最新写入立即可搜索。
/// </summary>
[HttpPost]
public async Task RefreshIndex()
{
await _searchService.RefreshIndexAsync();
}
/// <summary>
/// 手动新增或覆盖一条搜索文档。
/// </summary>
[HttpPost]
public async Task AddSearchDocument([FromBody] GoodsSearchDocument document)
{
if (document == null || document.Id <= 0)
{
throw new AppException("请提供有效的搜索文档", ResultCode.ValidationError);
}
await _searchService.AddDocumentAsync(document);
}
/// <summary>
/// 读取指定商品详情:解压缩原始数据并返回 JSON。
/// </summary>
[HttpGet]
public async Task<JsonNode> GetGoodsDetail([FromQuery] long goodsId)
{
var raw = await GetRawDataOrThrowAsync(goodsId);
var node = JsonNode.Parse(raw);
return node ?? throw new AppException("商品详情解析失败", ResultCode.BusinessError);
}
/// <summary>
/// 读取指定商品的原始数据(解压缩后原样返回)。
/// </summary>
[HttpGet]
public async Task<string> GetGoodsRawData([FromQuery] long goodsId)
{
return await GetRawDataOrThrowAsync(goodsId);
}
/// <summary>
/// 重新从数据库读取指定商品,覆盖 OpenSearch 已有分词并重新分词。
/// ids 为空时重建全部商品。
/// </summary>
[HttpPost]
public async Task<long> RebuildIndex([FromBody] long[]? ids)
{
return await _goodsService.RebuildSearchIndexAsync(ids);
}
/// <summary>
/// 删除商品(按商品编号)。是否软删除由配置 Delete:SoftDelete 决定,
/// 软删除将 Status 置 1,硬删除物理删除记录;两种方式都会删除 OpenSearch 中对应文档。
/// </summary>
[HttpPost]
public async Task<long> DeleteGoods([FromBody] long[]? ids)
{
if (ids == null || ids.Length == 0)
{
throw new AppException("请提供要删除的商品ID", ResultCode.ValidationError);
}
return await _goodsService.DeleteGoodsAsync(ids);
}
/// <summary>
/// 清空并重建搜索索引(路由保持 ClearSearch 不变)。
/// </summary>
[HttpGet]
[ActionName("ClearSearch")]
public async Task<bool> ClearSearchIndex()
{
return await _searchService.ClearIndexAsync();
}
/// <summary>
/// 统计索引中的文档数(路由保持 GetSearchCount 不变)。
/// </summary>
[HttpGet]
[ActionName("GetSearchCount")]
public async Task<long> GetSearchDocumentCount()
{
return await _searchService.CountDocumentsAsync();
}
private async Task<string> GetRawDataOrThrowAsync(long goodsId)
{
if (goodsId <= 0)
throw new AppException("商品ID无效", ResultCode.ValidationError);
var raw = await _rawDataStorage.ReadAsync(goodsId);
if (raw == null)
throw new AppException($"商品原始数据不存在: {goodsId}", ResultCode.NotFound);
return raw;
}
private static string GetDataFilePath()
{
var outputPath = Path.Combine(AppContext.BaseDirectory, "ImportConverters", "data.txt");
if (System.IO.File.Exists(outputPath))
return outputPath;
var workPath = Path.Combine(Directory.GetCurrentDirectory(), "ImportConverters", "data.txt");
if (System.IO.File.Exists(workPath))
return workPath;
return outputPath;
}
}
}
@@ -0,0 +1,20 @@
using Store.Modules.CloudProduct.Entities;
namespace Store.Modules.CloudProduct.Dtos
{
/// <summary>
/// 导入项:商品模型 + 原始数据
/// </summary>
public class GoodsImportItem
{
/// <summary>
/// 解析后的商品模型
/// </summary>
public GoodsEntity Goods { get; set; } = null!;
/// <summary>
/// 原始数据(JSON 原文,压缩后落盘)
/// </summary>
public string RawData { get; set; } = string.Empty;
}
}
@@ -0,0 +1,30 @@
using System.Collections.Generic;
namespace Store.Modules.CloudProduct.Dtos
{
/// <summary>
/// 商品导入结果
/// </summary>
public class GoodsImportResult
{
/// <summary>
/// 成功条数
/// </summary>
public int SuccessCount { get; set; }
/// <summary>
/// 失败条数
/// </summary>
public int FailedCount { get; set; }
/// <summary>
/// 总条数
/// </summary>
public int Total => SuccessCount + FailedCount;
/// <summary>
/// 错误明细
/// </summary>
public List<string> Errors { get; set; } = new();
}
}
@@ -0,0 +1,48 @@
using OpenSearch.Client;
namespace Store.Modules.CloudProduct.Dtos
{
/// <summary>
/// 商品搜索文档:OpenSearch 索引中的商品模型,Id 为主键,Title 用于分词搜索
/// </summary>
public class GoodsSearchDocument
{
[Number(NumberType.Byte, Name = "platform")]
public byte Platform { get; set; }
[Number(NumberType.Long, Name = "id")]
public long Id { get; set; }
[Text(Name = "title", Analyzer = "ik_max_word", SearchAnalyzer = "ik_smart")]
public string Title { get; set; } = string.Empty;
[Text(Name = "thumbUrl")]
public string? ThumbUrl { get; set; } = string.Empty;
/// <summary>一级类目ID</summary>
[Number(NumberType.Integer, Name = "cat_id_1")]
public int? CatId1 { get; set; }
/// <summary>二级类目ID</summary>
[Number(NumberType.Integer, Name = "cat_id_2")]
public int? CatId2 { get; set; }
/// <summary>三级类目ID</summary>
[Number(NumberType.Integer, Name = "cat_id_3")]
public int? CatId3 { get; set; }
/// <summary>四级类目ID</summary>
[Number(NumberType.Integer, Name = "cat_id_4")]
public int? CatId4 { get; set; }
/// <summary>最低价快照,用于价格区间过滤和按价格排序</summary>
[Number(NumberType.Long, Name = "min_price")]
public long? MinPrice { get; set; }
/// <summary>销量,用于按销量排序</summary>
[Number(NumberType.Integer, Name = "sold_quantity")]
public int SoldQuantity { get; set; }
public override string ToString() => $"[Id={Id}] Title={Title} Cat=({CatId1},{CatId2},{CatId3},{CatId4}) Price={MinPrice} Sold={SoldQuantity}";
}
}
@@ -0,0 +1,78 @@
namespace Store.Modules.CloudProduct.Dtos
{
/// <summary>
/// 商品搜索请求
/// </summary>
public class GoodsSearchRequest
{
/// <summary>
/// 标题(模糊搜索)
/// </summary>
public string Title { get; set; } = string.Empty;
/// <summary>
/// 最低价格(分)
/// </summary>
public long? MinPrice { get; set; }
/// <summary>
/// 最高价格(分)
/// </summary>
public long? MaxPrice { get; set; }
/// <summary>
/// 一级类目ID
/// </summary>
public int? CatId1 { get; set; }
/// <summary>
/// 二级类目ID
/// </summary>
public int? CatId2 { get; set; }
/// <summary>
/// 三级类目ID
/// </summary>
public int? CatId3 { get; set; }
/// <summary>
/// 四级类目ID
/// </summary>
public int? CatId4 { get; set; }
/// <summary>
/// 最低销量
/// </summary>
public int? MinSoldQuantity { get; set; }
/// <summary>
/// 最高销量
/// </summary>
public int? MaxSoldQuantity { get; set; }
/// <summary>
/// 平台类型
/// </summary>
public byte? Platform { get; set; }
/// <summary>
/// 页码(默认1)
/// </summary>
public int PageIndex { get; set; } = 1;
/// <summary>
/// 每页数量(默认20)
/// </summary>
public int PageSize { get; set; } = 20;
/// <summary>
/// 排序字段
/// </summary>
public string SortBy { get; set; } = "CreatedTime";
/// <summary>
/// 排序方式:asc/desc(默认desc)
/// </summary>
public string SortOrder { get; set; } = "desc";
}
}
@@ -0,0 +1,108 @@
namespace Store.Modules.CloudProduct.Dtos
{
/// <summary>
/// OpenSearch 运行状态
/// </summary>
public class OpenSearchStatusDto
{
/// <summary>
/// 节点地址
/// </summary>
public string NodeUrl { get; set; } = string.Empty;
/// <summary>
/// 索引名称
/// </summary>
public string IndexName { get; set; } = string.Empty;
/// <summary>
/// 是否可连接
/// </summary>
public bool Connected { get; set; }
/// <summary>
/// OpenSearch 服务及目标索引是否健康
/// </summary>
public bool Healthy { get; set; }
/// <summary>
/// 集群名称
/// </summary>
public string? ClusterName { get; set; }
/// <summary>
/// 集群状态(green、yellow 或 red)
/// </summary>
public string? ClusterStatus { get; set; }
/// <summary>
/// 集群节点总数
/// </summary>
public int NumberOfNodes { get; set; }
/// <summary>
/// 数据节点数量
/// </summary>
public int NumberOfDataNodes { get; set; }
/// <summary>
/// 活跃主分片数量
/// </summary>
public int ActivePrimaryShards { get; set; }
/// <summary>
/// 活跃分片总数
/// </summary>
public int ActiveShards { get; set; }
/// <summary>
/// 正在迁移的分片数量
/// </summary>
public int RelocatingShards { get; set; }
/// <summary>
/// 正在初始化的分片数量
/// </summary>
public int InitializingShards { get; set; }
/// <summary>
/// 未分配的分片数量
/// </summary>
public int UnassignedShards { get; set; }
/// <summary>
/// 索引是否存在
/// </summary>
public bool IndexExists { get; set; }
/// <summary>
/// 索引映射是否符合当前服务要求
/// </summary>
public bool MappingHealthy { get; set; }
/// <summary>
/// 标题字段的索引分析器
/// </summary>
public string? IndexAnalyzer { get; set; }
/// <summary>
/// 标题字段的搜索分析器
/// </summary>
public string? SearchAnalyzer { get; set; }
/// <summary>
/// 文档总数(索引不存在或读取失败时为 -1)
/// </summary>
public long DocumentCount { get; set; } = -1;
/// <summary>
/// 状态检测耗时(毫秒)
/// </summary>
public long ElapsedMilliseconds { get; set; }
/// <summary>
/// 状态说明或错误信息
/// </summary>
public string? Message { get; set; }
}
}
+120
View File
@@ -0,0 +1,120 @@
using FreeSql.DataAnnotations;
using System.Text.Json.Serialization;
namespace Store.Modules.CloudProduct.Entities
{
/// <summary>
/// 商品表实体(对应数据库表 goods)
/// </summary>
[Table(Name = "goods")]
public class GoodsEntity
{
/// <summary>
/// 自增ID
/// </summary>
[Column(IsPrimary = true, IsIdentity = true)]
[JsonIgnore]
public long Id { get; set; }
/// <summary>
/// 平台类型
/// 1 PDD
/// </summary>
[Column(IsNullable = false)]
public byte Platform { get; set; }
/// <summary>
/// 商品编号
/// </summary>
[Column(Name = "goods_id", IsNullable = false)]
public long GoodsId { get; set; }
/// <summary>
/// 标题
/// </summary>
[Column(Name = "title", IsNullable = false, StringLength = 500)]
public string Title { get; set; } = string.Empty;
/// <summary>
/// 描述
/// </summary>
[Column(Name = "description", IsNullable = true)]
public string? Description { get; set; }
/// <summary>
/// 缩略图
/// </summary>
[Column(Name = "thumb_url", IsNullable = true, StringLength = 512)]
public string? ThumbUrl { get; set; }
/// <summary>
/// 一级类目ID
/// </summary>
[Column(Name = "cat_id_1", IsNullable = true)]
public int? CatId1 { get; set; }
/// <summary>
/// 二级类目ID
/// </summary>
[Column(Name = "cat_id_2", IsNullable = true)]
public int? CatId2 { get; set; }
/// <summary>
/// 三级类目ID
/// </summary>
[Column(Name = "cat_id_3", IsNullable = true)]
public int? CatId3 { get; set; }
/// <summary>
/// 四级类目ID
/// </summary>
[Column(Name = "cat_id_4", IsNullable = true)]
public int? CatId4 { get; set; }
/// <summary>
/// 最低价快照(元),导入时计算
/// </summary>
[Column(Name = "min_price")]
public long? MinPrice { get; set; }
/// <summary>
/// 最高价快照(元),导入时计算
/// </summary>
[Column(Name = "max_price")]
public long? MaxPrice { get; set; }
/// <summary>
/// 销量
/// </summary>
[Column(Name = "sold_quantity", IsNullable = false)]
public int SoldQuantity { get; set; }
/// <summary>
/// 状态:0正常 1已删除
/// </summary>
[Column(IsNullable = false)]
[JsonIgnore]
public byte Status { get; set; }
/// <summary>
/// 创建时间
/// </summary>
[Column(Name = "createdTime", IsNullable = false, ServerTime = DateTimeKind.Utc)]
[JsonIgnore]
public DateTime CreatedTime { get; set; }
/// <summary>
/// 更新时间(自动更新)
/// </summary>
[Column(Name = "updatedTime", IsNullable = false, ServerTime = DateTimeKind.Utc)]
[JsonIgnore]
public DateTime UpdatedTime { get; set; }
/// <summary>
/// 是否已分词:0未 1已
/// </summary>
[Column(Name = "is_segmented", IsNullable = false)]
[JsonIgnore]
public byte IsSegmented { get; set; }
}
}
@@ -0,0 +1,20 @@
namespace Store.Modules.CloudProduct.Enums
{
/// <summary>
/// 搜索排序方式
/// </summary>
public enum GoodsSearchSortBy
{
/// <summary>相关性(默认)</summary>
Relevance = 0,
/// <summary>价格从低到高</summary>
PriceAsc = 1,
/// <summary>价格从高到低</summary>
PriceDesc = 2,
/// <summary>销量从高到低</summary>
SoldDesc = 3,
}
}
@@ -0,0 +1,9 @@
namespace Store.Modules.CloudProduct.Enums
{
public enum PlatformType
{
None = 0,
PDD = 1,
WX = 2,
}
}
@@ -0,0 +1,107 @@
using Store.Modules.CloudProduct.Entities;
using Store.Modules.CloudProduct.Enums;
using System.Text.Json.Nodes;
namespace Store.Modules.CloudProduct.ImportConverters
{
/// <summary>
/// 导入商品数据转换器
/// </summary>
public interface IGoodsConverter
{
/// <summary>
/// 原始数据(JSON 原文)
/// </summary>
string RawData { get; }
/// <summary>
/// 获取转换器名称
/// </summary>
string ConverterName { get; }
/// <summary>
/// 支持的平台类型
/// </summary>
PlatformType Platform { get; }
/// <summary>
/// 读取内容
/// </summary>
/// <param name="content">JSON 原文内容</param>
void ReadContent(string content);
/// <summary>
/// 判断是否匹配当前转换器
/// </summary>
/// <returns>是否匹配</returns>
bool IsMatch();
/// <summary>
/// 转换为标准商品模型
/// </summary>
GoodsEntity Convert();
}
/// <summary>
/// 转换器基类:统一实现读取、校验与转换骨架,子类只需实现匹配判定与字段映射。
/// </summary>
public abstract class GoodsConverter : IGoodsConverter
{
private bool _isMatch = false;
public string RawData { get; private set; } = null!;
public abstract string ConverterName { get; }
public abstract PlatformType Platform { get; }
void IGoodsConverter.ReadContent(string content)
{
ReadContent(content);
}
protected virtual void ReadContent(string content)
{
RawData = content;
}
public virtual bool IsMatch()
{
_isMatch = true;
return IsMatchCore();
}
/// <summary>
/// 由子类实现的具体匹配判定
/// </summary>
protected abstract bool IsMatchCore();
/// <summary>
/// 带校验的转换(基类统一实现)
/// </summary>
public virtual GoodsEntity Convert()
{
if (_isMatch == false) throw new Exception("未校验数据");
try
{
JsonNode.Parse(RawData);
}
catch { throw new Exception("数据解析失败,不是有效的JSON格式"); }
var goods = ConvertCore();
if (goods == null)
throw new Exception("转换失败");
// 基础校验
if (goods.GoodsId == 0)
throw new Exception("商品ID不能为空");
return goods;
}
/// <summary>
/// 由子类实现的具体字段映射
/// </summary>
protected abstract GoodsEntity ConvertCore();
}
}
@@ -0,0 +1,54 @@
using Store.Modules.CloudProduct.Entities;
using System.Collections.Generic;
using System.IO;
namespace Store.Modules.CloudProduct.ImportConverters
{
/// <summary>
/// 导入商品转换工厂:按顺序尝试各转换器,返回标准商品模型。
/// </summary>
public class GoodsConverterFactory
{
private static readonly List<IGoodsConverter> _converters = new List<IGoodsConverter>
{
new PddGoodsConverter(),
};
/// <summary>
/// 根据本地 JSON 文件路径转换。
/// </summary>
public static GoodsEntity? Convert(string filePath)
{
if (string.IsNullOrWhiteSpace(filePath))
throw new ArgumentNullException(nameof(filePath));
if (!File.Exists(filePath))
throw new FileNotFoundException("找不到导入文件", filePath);
var content = File.ReadAllText(filePath);
return ConvertContent(content);
}
/// <summary>
/// 根据 JSON 内容字符串转换。
/// </summary>
public static GoodsEntity? ConvertContent(string content)
{
if (string.IsNullOrWhiteSpace(content))
throw new ArgumentNullException(nameof(content));
foreach (var converter in _converters)
{
converter.ReadContent(content);
if (converter.IsMatch())
{
var goods = converter.Convert();
if (goods != null)
return goods;
}
}
return null;
}
}
}
@@ -0,0 +1,176 @@
using Store.Modules.CloudProduct.Entities;
using Store.Modules.CloudProduct.Enums;
using System.Text.Json.Nodes;
namespace Store.Modules.CloudProduct.ImportConverters
{
/// <summary>
/// PDD 前端商品详情数据转换器(数据源格式见 data.txt)
/// </summary>
internal class PddGoodsConverter : GoodsConverter
{
public override string ConverterName => nameof(PddGoodsConverter);
public override PlatformType Platform => PlatformType.PDD;
protected override bool IsMatchCore()
{
try
{
if (JsonNode.Parse(RawData) is not JsonObject root)
return false;
// data.txt:顶层包含 goods.goods_id
if (root["goods"] is JsonObject goodsObj && goodsObj["goods_id"] != null)
return true;
// 也兼容顶层直接是商品对象的情况
if (root["goods_id"] != null && (root["goods_name"] != null || root["title"] != null))
return true;
return false;
}
catch
{
return false;
}
}
protected override GoodsEntity ConvertCore()
{
if (JsonNode.Parse(RawData) is not JsonObject root)
throw new Exception("无法解析 PDD 商品数据");
var goodsNode = root["goods"] as JsonObject ?? root;
var priceNode = root["price"] as JsonObject;
var goods = new GoodsEntity
{
Platform = (byte)PlatformType.PDD,
GoodsId = GetLong(goodsNode, "goods_id"),
Title = GetString(goodsNode, "goods_name")
?? GetString(goodsNode, "short_name")
?? string.Empty,
Description = GetString(goodsNode, "share_desc") ?? GetString(goodsNode, "short_name"),
ThumbUrl = GetString(goodsNode, "hd_url") ?? GetString(goodsNode, "thumb_url") ?? GetString(goodsNode, "hd_thumb_url") ?? GetString(goodsNode, "image_url"),
CatId1 = GetIntOrNull(goodsNode, "cat_id_1"),
CatId2 = GetIntOrNull(goodsNode, "cat_id_2"),
CatId3 = GetIntOrNull(goodsNode, "cat_id_3"),
CatId4 = GetIntOrNull(goodsNode, "cat_id_4"),
SoldQuantity = GetInt(goodsNode, "sold_quantity"),
Status = 0,
};
var price = GetPriceRange(priceNode, root);
goods.MinPrice = price.Min;
goods.MaxPrice = price.Max;
return goods;
}
private static string? GetString(JsonObject? obj, string key)
{
if (obj == null || !obj.TryGetPropertyValue(key, out var node) || node == null)
return null;
if (node is JsonValue value && value.TryGetValue<string>(out var str))
return str;
return node.ToJsonString();
}
private static long GetLong(JsonObject? obj, string key)
{
if (obj == null || !obj.TryGetPropertyValue(key, out var node) || node == null)
return 0;
if (node is JsonValue value)
{
if (value.TryGetValue<long>(out var l)) return l;
if (value.TryGetValue<decimal>(out var d)) return (long)d;
if (long.TryParse(value.ToString(), out var l2)) return l2;
}
return 0;
}
private static int GetInt(JsonObject? obj, string key)
{
if (obj == null || !obj.TryGetPropertyValue(key, out var node) || node == null)
return 0;
if (node is JsonValue value)
{
if (value.TryGetValue<int>(out var i)) return i;
if (value.TryGetValue<long>(out var l)) return (int)l;
if (int.TryParse(value.ToString(), out var i2)) return i2;
}
return 0;
}
private static int? GetIntOrNull(JsonObject? obj, string key)
{
if (obj == null || !obj.TryGetPropertyValue(key, out var node) || node == null)
return null;
if (node is JsonValue value)
{
if (value.TryGetValue<int>(out var i) && i > 0) return i;
if (value.TryGetValue<long>(out var l) && l > 0) return (int)l;
if (int.TryParse(value.ToString(), out var i2) && i2 > 0) return i2;
}
return null;
}
private static long? GetLongOrNull(JsonObject? obj, string key)
{
if (obj == null || !obj.TryGetPropertyValue(key, out var node) || node == null)
return null;
if (node is JsonValue value)
{
if (value.TryGetValue<long>(out var d)) return d;
if (value.TryGetValue<long>(out var l)) return l;
if (long.TryParse(value.ToString(), out var d2)) return d2;
}
return null;
}
/// <summary>
/// 计算价格区间。优先使用顶层 price 节点,其次遍历 sku。
/// </summary>
private static (long? Min, long? Max) GetPriceRange(JsonObject? priceNode, JsonObject root)
{
long? min = null;
long? max = null;
if (priceNode != null)
{
min = GetLongOrNull(priceNode, "min_group_price");
max = GetLongOrNull(priceNode, "max_group_price");
if (min.HasValue || max.HasValue)
return (min, max);
}
if (root["sku"] is JsonArray skuArray && skuArray.Count > 0)
{
foreach (var item in skuArray.OfType<JsonObject>())
{
var price = GetLongOrNull(item, "group_price") ?? GetLongOrNull(item, "normal_price");
if (price == null) continue;
min = min.HasValue ? Math.Min(min.Value, price.Value) : price;
max = max.HasValue ? Math.Max(max.Value, price.Value) : price;
}
if (min.HasValue || max.HasValue)
return (min, max);
}
return (null, null);
}
}
}
@@ -0,0 +1,17 @@
using FreeSql;
using MAX.Core.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using Store.Modules.CloudProduct.Entities;
namespace Store.Modules.CloudProduct.Repositorys
{
/// <summary>
/// 商品仓储(对应 goods 表)
/// </summary>
public class GoodsRepository : BaseRepository<GoodsEntity>, IScopedDependency
{
public GoodsRepository([FromKeyedServices("CloudProductConnection")] IFreeSql fsql) : base(fsql)
{
}
}
}
@@ -0,0 +1,32 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace Store.Modules.CloudProduct.Services
{
/// <summary>
/// Hangfire 定时任务:把数据库中未同步(IndexStatus=0)的商品写入 OpenSearch 分词索引。
/// </summary>
public class GoodsIndexJob
{
private readonly IServiceScopeFactory _scopeFactory;
private readonly IConfiguration _configuration;
private readonly ILogger<GoodsIndexJob> _logger;
public GoodsIndexJob(IServiceScopeFactory scopeFactory, IConfiguration configuration,ILogger<GoodsIndexJob> logger)
{
_scopeFactory = scopeFactory;
_configuration = configuration;
_logger = logger;
}
public async Task ProcessPendingAsync()
{
var batchSize = _configuration.GetValue<int?>("Indexing:BatchSize") ?? 1000;
using var scope = _scopeFactory.CreateScope();
var service = scope.ServiceProvider.GetRequiredService<GoodsService>();
var count = await service.IndexPendingGoodsAsync(batchSize);
_logger.LogInformation($"[Hangfire] 商品分词定时任务完成,本次同步 {count} 条");
}
}
}
@@ -0,0 +1,402 @@
using MAX.Core.DependencyInjection;
using Microsoft.Extensions.Configuration;
using Store.Modules.CloudProduct.Dtos;
using Store.Modules.CloudProduct.Entities;
using Store.Modules.CloudProduct.Repositorys;
namespace Store.Modules.CloudProduct.Services
{
public interface IGoodsService : IScopedDependency
{
Task<int> DeleteGoodsAsync(IEnumerable<long> ids);
Task<List<GoodsEntity>> GetGoodsByGoodsIdsAsync(IEnumerable<long> goodsIds);
Task<GoodsImportResult> ImportGoodsAsync(IEnumerable<GoodsImportItem> items);
Task<int> IndexPendingGoodsAsync(int batchSize);
Task<long> RebuildSearchIndexAsync(IEnumerable<long>? ids = null);
Task<(List<GoodsEntity> List, long Total)> SearchGoodsAsync(GoodsSearchRequest request);
Task<int> UpdateThumbUrlAsync(IEnumerable<GoodsEntity> goodsList);
}
internal class GoodsService : IGoodsService
{
private readonly GoodsRepository _repository;
private readonly IOpenSearchService _searchService;
private readonly IRawDataStorage _rawDataStorage;
private readonly IConfiguration _configuration;
public GoodsService(GoodsRepository repository, IOpenSearchService searchService, IRawDataStorage rawDataStorage, IConfiguration configuration)
{
_repository = repository;
_searchService = searchService;
_rawDataStorage = rawDataStorage;
_configuration = configuration;
}
public async Task<(List<GoodsEntity> List, long Total)> SearchGoodsAsync(GoodsSearchRequest request)
{
// 1. 从搜索引擎获取标题匹配的商品
var searchResult = await _searchService.SearchByTitleAsync(request);
var goodsList = searchResult.Documents.Select(a => new GoodsEntity
{
Platform = a.Platform,
GoodsId = a.Id,
Title = a.Title,
CatId1 = a.CatId1,
CatId2 = a.CatId2,
CatId3 = a.CatId3,
CatId4 = a.CatId4,
MinPrice = a.MinPrice,
MaxPrice = 0,
SoldQuantity = a.SoldQuantity,
ThumbUrl = a.ThumbUrl,
}).ToList();
return (goodsList, searchResult.Total);
//// 2. 构建数据库查询(只查正常状态,排除软删除)
//var query = _repository.Select.Where(x => x.Status == 0);
//// 如果有标题搜索,先用ID过滤
//if (goodsIds.Any())
//{
// query = query.Where(x => goodsIds.Contains(x.GoodsId));
//}
//// 3. 价格区间查询
//if (request.MinPrice.HasValue)
//{
// query = query.Where(x => x.MinPrice >= request.MinPrice.Value);
//}
//if (request.MaxPrice.HasValue)
//{
// query = query.Where(x => x.MaxPrice <= request.MaxPrice.Value);
//}
//// 4. 类目查询
//if (request.CatId1.HasValue)
//{
// query = query.Where(x => x.CatId1 == request.CatId1);
//}
//if (request.CatId2.HasValue)
//{
// query = query.Where(x => x.CatId2 == request.CatId2);
//}
//if (request.CatId3.HasValue)
//{
// query = query.Where(x => x.CatId3 == request.CatId3);
//}
//if (request.CatId4.HasValue)
//{
// query = query.Where(x => x.CatId4 == request.CatId4);
//}
//// 5. 销量区间查询
//if (request.MinSoldQuantity.HasValue)
//{
// query = query.Where(x => x.SoldQuantity >= request.MinSoldQuantity.Value);
//}
//if (request.MaxSoldQuantity.HasValue)
//{
// query = query.Where(x => x.SoldQuantity <= request.MaxSoldQuantity.Value);
//}
//// 6. 平台过滤
//if (request.Platform.HasValue)
//{
// query = query.Where(x => x.Platform == request.Platform);
//}
//// 8. 获取总数
//total = await query.CountAsync();
//// 9. 排序
//if (!string.IsNullOrEmpty(request.SortBy))
//{
// var isAsc = request.SortOrder?.ToLower() == "asc";
// query = query.OrderByPropertyName(request.SortBy, isAsc);
//}
//else
//{
// query = query.OrderByDescending(x => x.CreatedTime);
//}
//// 10. 分页查询
//var list = await query
// //.Skip((request.PageIndex - 1) * request.PageSize)
// //.Limit(request.PageSize)
// .ToListAsync();
////内存排序
//var orderMap = goodsIds.Select((id, idx) => new { id, idx })
// .ToDictionary(x => x.id, x => x.idx);
//list = list.OrderBy(x => orderMap.TryGetValue(x.GoodsId, out var idx) ? idx : int.MaxValue)
// .ToList();
//return (list, total);
}
/// <summary>
/// 批量导入商品:先落库(按平台 + 商品编号去重)+ 保存原始数据,
/// 然后根据配置决定“立即分词”还是“标记未同步交给后台任务分词”。
/// </summary>
public async Task<GoodsImportResult> ImportGoodsAsync(IEnumerable<GoodsImportItem> items)
{
var result = new GoodsImportResult();
if (items == null)
return result;
var indexImmediately = IsImmediateIndexing();
var documents = new List<GoodsSearchDocument>();
var indexedIds = new List<long>();
foreach (var item in items)
{
var goods = item?.Goods;
if (goods == null)
{
result.FailedCount++;
result.Errors.Add("商品数据为空");
continue;
}
var goodsId = goods.GoodsId;
if (goodsId == 0)
{
result.FailedCount++;
result.Errors.Add("商品编号(GoodsId)不能为空");
continue;
}
try
{
// 导入时统一先标记“未同步”;立即分词成功后再置为“已同步”,
// 后台模式下保持“未同步”,由 Hangfire 定时任务分词。
goods.IsSegmented = 0;
var saved = await UpsertGoodsAsync(goods);
var rawData = item?.RawData ?? string.Empty;
if (!string.IsNullOrWhiteSpace(rawData))
{
await _rawDataStorage.SaveAsync(saved.GoodsId, rawData);
}
if (indexImmediately)
{
documents.Add(new GoodsSearchDocument
{
Platform = saved.Platform,
Id = saved.GoodsId,
Title = saved.Title ?? string.Empty,
ThumbUrl = saved.ThumbUrl,
CatId1 = saved.CatId1,
CatId2 = saved.CatId2,
CatId3 = saved.CatId3,
CatId4 = saved.CatId4,
MinPrice = saved.MinPrice,
SoldQuantity = saved.SoldQuantity,
});
indexedIds.Add(saved.GoodsId);
}
result.SuccessCount++;
}
catch (Exception ex)
{
result.FailedCount++;
result.Errors.Add($"GoodsId={goodsId}: {ex.Message}");
}
}
if (documents.Count > 0)
{
try
{
await _searchService.BulkIndexGoodsAsync(documents);
await MarkIndexedAsync(indexedIds);
}
catch (Exception ex)
{
// 写入失败时保持“未同步”,由后台定时任务重试
result.FailedCount += documents.Count;
result.SuccessCount -= documents.Count;
result.Errors.Add("写入 OpenSearch 失败: " + ex.Message);
}
}
return result;
}
/// <summary>
/// 后台任务:批量处理未同步(IsSegmented=0)的商品,写入 OpenSearch 后标记为已同步。
/// </summary>
public async Task<int> IndexPendingGoodsAsync(int batchSize)
{
if (batchSize <= 0)
batchSize = 200;
var pending = await _repository.Select
.Where(x => x.IsSegmented == 0 && x.Status == 0)
.OrderBy(x => x.GoodsId)
.Limit(batchSize)
.ToListAsync();
if (pending.Count == 0)
return 0;
var documents = pending
.Select(x => new GoodsSearchDocument
{
Platform = x.Platform,
Id = x.GoodsId,
Title = x.Title ?? string.Empty,
ThumbUrl = x.ThumbUrl,
CatId1 = x.CatId1,
CatId2 = x.CatId2,
CatId3 = x.CatId3,
CatId4 = x.CatId4,
MinPrice = x.MinPrice,
SoldQuantity = x.SoldQuantity,
})
.ToList();
await _searchService.BulkIndexGoodsAsync(documents);
await MarkIndexedAsync(pending.Select(x => x.GoodsId));
return pending.Count;
}
/// <summary>
/// 按平台 + 商品编号查找已存在记录,存在则更新,不存在则新增。
/// </summary>
private async Task<GoodsEntity> UpsertGoodsAsync(GoodsEntity goods)
{
var existing = await _repository.Select
.Where(x => x.Platform == goods.Platform && x.GoodsId == goods.GoodsId)
.FirstAsync();
if (existing != null)
{
goods.Id = existing.Id;
goods.GoodsId = existing.GoodsId;
goods.CreatedTime = existing.CreatedTime;
goods.UpdatedTime = DateTime.Now;
await _repository.UpdateAsync(goods);
return goods;
}
goods.CreatedTime = DateTime.Now;
goods.UpdatedTime = DateTime.Now;
return await _repository.InsertAsync(goods);
}
/// <summary>
/// 根据商品编号(GoodsId)列表读取商品。
/// </summary>
public async Task<List<GoodsEntity>> GetGoodsByGoodsIdsAsync(IEnumerable<long> goodsIds)
{
var idList = goodsIds?.ToList();
if (idList == null || idList.Count == 0)
return new List<GoodsEntity>();
return await _repository.Select
.Where(x => idList.Contains(x.GoodsId))
.ToListAsync();
}
/// <summary>
/// 重新从数据库读取指定商品,覆盖 OpenSearch 中已有的分词并重新分词。
/// ids 为空时重建全部商品。重建成功的记录标记为已同步。
/// </summary>
public async Task<long> RebuildSearchIndexAsync(IEnumerable<long>? ids = null)
{
List<GoodsEntity> goodsList;
var idList = ids?.ToList();
if (idList == null || idList.Count == 0)
{
goodsList = await _repository.Select.ToListAsync();
}
else
{
goodsList = await _repository.Select
.Where(x => idList.Contains(x.GoodsId))
.ToListAsync();
}
var count = await _searchService.RebuildIndexAsync(goodsList);
await MarkIndexedAsync(goodsList.Where(x => x.GoodsId > 0).Select(x => x.GoodsId));
return count;
}
/// <summary>
/// 删除商品:按配置决定软删除(Status=1)还是硬删除(物理删除),
/// 两种方式都会删除 OpenSearch 中对应的文档。
/// </summary>
public async Task<int> DeleteGoodsAsync(IEnumerable<long> ids)
{
var idList = ids?.Distinct().ToList();
if (idList == null || idList.Count == 0)
return 0;
if (IsSoftDelete())
{
// 软删除:仅用 Status 标记(0正常 1已删除)
await _repository.Orm.Update<GoodsEntity>()
.Set(x => x.Status, (byte)1)
.Where(x => idList.Contains(x.GoodsId))
.ExecuteAffrowsAsync();
}
else
{
// 硬删除:直接删除数据库记录
await _repository.Orm.Delete<GoodsEntity>()
.Where(x => idList.Contains(x.GoodsId))
.ExecuteAffrowsAsync();
}
// 无论软删除还是硬删除,都要删除 OpenSearch 中的对应文档
await _searchService.DeleteDocumentsAsync(idList);
return idList.Count;
}
/// <summary>
/// 批量更新商品缩略图。
/// </summary>
public async Task<int> UpdateThumbUrlAsync(IEnumerable<GoodsEntity> goodsList)
{
//string sql = _repository.Orm.Update<GoodsEntity>().SetSource(goodsList, a => a.GoodsId).UpdateColumns(a => new { a.ThumbUrl }).ToSql();
return await _repository.Orm.Update<GoodsEntity>()
.SetSource(goodsList, a => a.GoodsId)
.UpdateColumns(a => new { a.ThumbUrl })
.ExecuteAffrowsAsync();
}
/// <summary>
/// 是否导入时立即分词(Indexing:Mode = Immediate)。
/// </summary>
private bool IsImmediateIndexing()
{
var mode = _configuration.GetValue<string>("Indexing:Mode");
return string.Equals(mode, "Immediate", StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// 是否软删除(Delete:SoftDelete,默认 true)。
/// </summary>
private bool IsSoftDelete()
{
return _configuration.GetValue<bool?>("Delete:SoftDelete") ?? true;
}
private async Task MarkIndexedAsync(IEnumerable<long> ids)
{
var idList = ids?.ToList();
if (idList == null || idList.Count == 0)
return;
await _repository.Orm.Update<GoodsEntity>()
.Set(x => x.IsSegmented, (byte)1)
.Where(x => idList.Contains(x.GoodsId))
.ExecuteAffrowsAsync();
}
}
}
@@ -0,0 +1,545 @@
using System.Diagnostics;
using MAX.Core.DependencyInjection;
using MAX.Framework.Commons;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using OpenSearch.Client;
using OpenSearch.Net;
using Store.Modules.CloudProduct.Dtos;
using Store.Modules.CloudProduct.Entities;
using Store.Modules.CloudProduct.Enums;
namespace Store.Modules.CloudProduct.Services
{
public interface IOpenSearchService : ISingletonDependency
{
Task AddDocumentAsync(GoodsSearchDocument document);
Task BulkIndexGoodsAsync(IEnumerable<GoodsSearchDocument> documents);
Task<bool> ClearIndexAsync();
Task<long> CountDocumentsAsync();
Task<bool> CreateIndexAsync();
Task DeleteDocumentsAsync(IEnumerable<long> ids);
Task DeleteIndexAsync();
Task<OpenSearchStatusDto> GetStatusAsync();
Task<bool> IndexExistsAsync();
Task<bool> IsIndexMappingHealthyAsync();
Task RefreshIndexAsync();
Task<long> RebuildIndexAsync(IEnumerable<GoodsEntity> goodsList);
Task<(long Total, List<GoodsSearchDocument> Documents)> SearchByTitleAsync(GoodsSearchRequest request, GoodsSearchSortBy sortBy = GoodsSearchSortBy.Relevance);
}
internal class OpenSearchService : IOpenSearchService
{
private readonly string _nodeUrl;
private readonly string _indexName;
private readonly IOpenSearchClient _client = null!;
// 查询类操作(search/count/status/ping)统一超时
private static readonly TimeSpan QueryTimeout = TimeSpan.FromSeconds(5);
// 批量写入/建索引/删除索引等管理类操作超时(数据量大时需要更长,可挪到配置文件)
private static readonly TimeSpan AdminTimeout = TimeSpan.FromSeconds(30);
private readonly ILogger<OpenSearchService> _logger;
public OpenSearchService(IConfiguration configuration,ILogger<OpenSearchService> logger)
{
var config = configuration.GetSection("Search");
_nodeUrl = config.GetValue<string>("Url") ?? "";
_indexName = config.GetValue<string>("IndexName") ?? "";
_client = CreateClient();
_logger = logger;
}
private IOpenSearchClient CreateClient()
{
var pool = new SingleNodeConnectionPool(new Uri(_nodeUrl));
var settings = new ConnectionSettings(pool)
.DefaultIndex(_indexName)
.DefaultMappingFor<GoodsSearchDocument>(m => m.IndexName(_indexName))
.RequestTimeout(QueryTimeout)
.MaxRetryTimeout(QueryTimeout)
.PrettyJson()
.DisableDirectStreaming(); // 便于调试打印请求/响应报文
return new OpenSearchClient(settings);
}
/// <summary>
/// ============ 1. 创建索引 ============
/// </summary>
public async Task<bool> CreateIndexAsync()
{
var existsResponse = await _client.Indices.ExistsAsync(_indexName, d => d
.RequestConfiguration(r => r.RequestTimeout(AdminTimeout)));
if (existsResponse.Exists)
{
if (await IsIndexMappingHealthyAsync())
{
Console.WriteLine($"索引 [{_indexName}] 已存在且映射正确,无需重复创建。");
return true;
}
Console.WriteLine($"索引 [{_indexName}] 的映射不完整(可能由清空索引等操作造成),正在重建...");
var deleteResponse = await _client.Indices.DeleteAsync(_indexName, d => d
.RequestConfiguration(r => r.RequestTimeout(AdminTimeout)));
if (!deleteResponse.IsValid)
{
throw new AppException("删除损坏索引失败: " + deleteResponse.DebugInformation);
}
}
// 优先尝试使用 IK 中文分词(需集群安装 analysis-ik 插件)
var createResponse = await TryCreateIndexAsync(useIk: true);
if (!createResponse.IsValid)
{
Console.WriteLine("IK 分词插件不可用,已回退到 standard 分析器,中文分词将失效,请检查集群是否安装 analysis-ik 插件。");
createResponse = await TryCreateIndexAsync(useIk: false);
}
if (createResponse.IsValid)
{
Console.WriteLine($"索引 [{_indexName}] 创建成功。");
return true;
}
else
{
throw new AppException("索引创建失败: " + createResponse.DebugInformation);
}
}
public async Task<bool> IsIndexMappingHealthyAsync()
{
var mappingStatus = await GetIndexMappingStatusAsync();
return mappingStatus.Healthy;
}
private async Task<(bool Healthy, string? IndexAnalyzer, string? SearchAnalyzer)> GetIndexMappingStatusAsync()
{
var getResponse = await _client.Indices.GetAsync(_indexName, d => d
.RequestConfiguration(r => r.RequestTimeout(QueryTimeout)));
if (!getResponse.IsValid)
{
throw new AppException("读取索引映射失败: " + getResponse.DebugInformation);
}
if (!getResponse.Indices.TryGetValue(_indexName, out var indexState))
{
return (false, null, null);
}
var mapping = indexState.Mappings;
if (mapping?.Properties == null
|| !mapping.Properties.TryGetValue(new PropertyName("title"), out var property)
|| property is not ITextProperty textProperty)
{
return (false, null, null);
}
var indexAnalyzer = textProperty.Analyzer;
var searchAnalyzer = textProperty.SearchAnalyzer;
var usesIk = indexAnalyzer == "ik_max_word" && searchAnalyzer == "ik_smart";
var usesStandard = indexAnalyzer == "standard" && searchAnalyzer == "standard";
return (usesIk || usesStandard, indexAnalyzer, searchAnalyzer);
}
private async Task<CreateIndexResponse> TryCreateIndexAsync(bool useIk)
{
var indexAnalyzer = useIk ? "ik_max_word" : "standard";
var searchAnalyzer = useIk ? "ik_smart" : "standard";
return await _client.Indices.CreateAsync(_indexName, c => c
.Settings(s => s
.NumberOfShards(1)
.NumberOfReplicas(0)
)
.Map<GoodsSearchDocument>(m => m
.Properties(p => p
.Number(n => n.Name(x => x.Id).Type(NumberType.Long))
.Text(t => t
.Name(x => x.Title)
.Analyzer(indexAnalyzer)
.SearchAnalyzer(searchAnalyzer)
)
.Number(n => n.Name(x => x.CatId1).Type(NumberType.Integer))
.Number(n => n.Name(x => x.CatId2).Type(NumberType.Integer))
.Number(n => n.Name(x => x.CatId3).Type(NumberType.Integer))
.Number(n => n.Name(x => x.CatId4).Type(NumberType.Integer))
.Number(n => n.Name(x => x.MinPrice).Type(NumberType.Long))
.Number(n => n.Name(x => x.SoldQuantity).Type(NumberType.Integer))
)
)
.RequestConfiguration(r => r.RequestTimeout(AdminTimeout))
);
}
/// <summary>
/// ============ 2. 删除索引 ============
/// </summary>
public async Task DeleteIndexAsync()
{
var response = await _client.Indices.DeleteAsync(_indexName, d => d
.RequestConfiguration(r => r.RequestTimeout(AdminTimeout)));
if (!response.IsValid)
{
throw new AppException("删除失败: " + response.DebugInformation);
}
}
public async Task<bool> IndexExistsAsync()
{
var response = await _client.Indices.ExistsAsync(_indexName, d => d
.RequestConfiguration(r => r.RequestTimeout(QueryTimeout)));
return response.Exists;
}
public async Task RefreshIndexAsync()
{
var response = await _client.Indices.RefreshAsync(_indexName, d => d
.RequestConfiguration(r => r.RequestTimeout(AdminTimeout)));
if (!response.IsValid)
{
throw new AppException("刷新索引失败: " + response.DebugInformation);
}
}
/// <summary>
/// ============ 3.1 批量写入商品搜索文档(存在则覆盖) ============
/// </summary>
public async Task BulkIndexGoodsAsync(IEnumerable<GoodsSearchDocument> documents)
{
if (documents == null) throw new ArgumentNullException(nameof(documents));
var list = documents.ToList();
if (list.Count == 0) return;
// 确保索引已按 IK 分词映射创建,否则中文分词无效
await CreateIndexAsync();
var bulkResponse = await _client.BulkAsync(b => b
.Index(_indexName)
.IndexMany(list, (descriptor, doc) => descriptor.Id(doc.Id))
.RequestConfiguration(r => r.RequestTimeout(AdminTimeout))
);
if (!bulkResponse.IsValid)
{
throw new AppException("写入 OpenSearch 失败: " + bulkResponse.DebugInformation);
}
// 刷新索引,保证数据立即可搜索(仅用于演示,生产环境不建议频繁 Refresh)
await RefreshIndexAsync();
}
/// <summary>
/// ============ 3.2 根据数据库商品重建搜索索引 ============
/// </summary>
public async Task<long> RebuildIndexAsync(IEnumerable<GoodsEntity> goodsList)
{
if (goodsList == null) throw new ArgumentNullException(nameof(goodsList));
var documents = goodsList
.Where(x => x != null && x.GoodsId > 0)
.Select(x => new GoodsSearchDocument
{
Id = x.GoodsId,
Title = x.Title ?? string.Empty,
CatId1 = x.CatId1,
CatId2 = x.CatId2,
CatId3 = x.CatId3,
CatId4 = x.CatId4,
MinPrice = x.MinPrice,
SoldQuantity = x.SoldQuantity
})
.ToList();
if (documents.Count == 0) return 0;
await BulkIndexGoodsAsync(documents);
return documents.Count;
}
/// <summary>
/// ============ 3.3 按商品编号批量删除 OpenSearch 文档(软/硬删除共用) ============
/// </summary>
public async Task DeleteDocumentsAsync(IEnumerable<long> ids)
{
var list = ids?.Distinct().ToList() ?? new List<long>();
if (list.Count == 0) return;
var exists = await _client.Indices.ExistsAsync(_indexName, d => d
.RequestConfiguration(r => r.RequestTimeout(QueryTimeout)));
if (!exists.Exists)
{
return;
}
var response = await _client.BulkAsync(b =>
{
foreach (var id in list)
{
b.Delete<GoodsSearchDocument>(d => d.Index(_indexName).Id(id));
}
b.RequestConfiguration(r => r.RequestTimeout(AdminTimeout));
return b;
});
if (!response.IsValid)
{
throw new AppException("删除 OpenSearch 文档失败: " + response.DebugInformation);
}
await RefreshIndexAsync();
}
/// <summary>
/// ============ 4. 手动新增一条搜索文档 ============
/// </summary>
public async Task AddDocumentAsync(GoodsSearchDocument document)
{
if (document == null) throw new ArgumentNullException(nameof(document));
var response = await _client.IndexAsync(document, i => i
.Index(_indexName)
.Id(document.Id)
.RequestConfiguration(r => r.RequestTimeout(QueryTimeout))
);
if (response.IsValid)
{
await RefreshIndexAsync();
}
else
{
throw new AppException("新增失败: " + response.DebugInformation);
}
}
/// <summary>
/// ============ 5. 分词搜索(分页 + 类目/价格/销量/平台过滤 + 排序) ============
/// </summary>
/// <param name="request">搜索条件(关键词、类目、价格、销量、平台、分页)</param>
/// <param name="sortBy">排序方式</param>
public async Task<(long Total, List<GoodsSearchDocument> Documents)> SearchByTitleAsync(GoodsSearchRequest request,
GoodsSearchSortBy sortBy = GoodsSearchSortBy.Relevance)
{
var keyword = request.Title;
int? catId1 = request.CatId1;
int? catId2 = request.CatId2;
int? catId3 = request.CatId3;
int? catId4 = request.CatId4;
long? minPrice = request.MinPrice;
long? maxPrice = request.MaxPrice;
int? minSoldQuantity = request.MinSoldQuantity;
int? maxSoldQuantity = request.MaxSoldQuantity;
int? platform = request.Platform;
int pageIndex = request.PageIndex;
int pageSize = request.PageSize;
if (pageIndex < 1) pageIndex = 1;
if (pageSize < 1) pageSize = 20;
if (pageSize > 2000) pageSize = 2000; // 避免深分页/单页过大拖垮性能,按需调整上限
var from = (pageIndex - 1) * pageSize;
ISearchResponse<GoodsSearchDocument> searchResponse;
try
{
searchResponse = await _client.SearchAsync<GoodsSearchDocument>(s => s
.Index(_indexName)
.Query(q => q
.Bool(b =>
{
if (string.IsNullOrWhiteSpace(keyword) == false)
{
b.Must(m => m.Match(mm => mm.Field(f => f.Title).Query(keyword)));
}
var filters = new List<Func<QueryContainerDescriptor<GoodsSearchDocument>, QueryContainer>>();
if (platform.HasValue && platform!.Value > 0) filters.Add(f => f.Term(t => t.Field(x => x.Platform).Value(platform.Value)));
if (catId1.HasValue) filters.Add(f => f.Term(t => t.Field(x => x.CatId1).Value(catId1.Value)));
if (catId2.HasValue) filters.Add(f => f.Term(t => t.Field(x => x.CatId2).Value(catId2.Value)));
if (catId3.HasValue) filters.Add(f => f.Term(t => t.Field(x => x.CatId3).Value(catId3.Value)));
if (catId4.HasValue) filters.Add(f => f.Term(t => t.Field(x => x.CatId4).Value(catId4.Value)));
if (minPrice.HasValue || maxPrice.HasValue)
{
filters.Add(f => f.Range(r =>
{
var range = r.Field(x => x.MinPrice);
if (minPrice.HasValue) range = range.GreaterThanOrEquals(minPrice.Value);
if (maxPrice.HasValue) range = range.LessThanOrEquals(maxPrice.Value);
return range;
}));
}
if (minSoldQuantity.HasValue || maxSoldQuantity.HasValue)
{
filters.Add(f => f.Range(r =>
{
var range = r.Field(x => x.SoldQuantity);
if (minSoldQuantity.HasValue) range = range.GreaterThanOrEquals(minSoldQuantity.Value);
if (maxSoldQuantity.HasValue) range = range.LessThanOrEquals(maxSoldQuantity.Value);
return range;
}));
}
if (filters.Count > 0) b.Filter(filters.ToArray());
return b;
})
)
.Sort(sort => sortBy switch
{
GoodsSearchSortBy.PriceAsc => sort.Ascending(f => f.MinPrice),
GoodsSearchSortBy.PriceDesc => sort.Descending(f => f.MinPrice),
GoodsSearchSortBy.SoldDesc => sort.Descending(f => f.SoldQuantity),
_ => sort.Descending(SortSpecialField.Score)
})
.From(from)
.Size(pageSize)
.TrackTotalHits(true) // 命中数超过 10000 时默认不精确统计,需要显式开启
.RequestConfiguration(r => r.RequestTimeout(QueryTimeout))
);
}
catch (OpenSearchClientException ex) when (ex.Response?.Success == false)
{
throw new AppException($"搜索超时或失败({QueryTimeout.TotalSeconds}秒): " + ex.Message);
}
if (!searchResponse.IsValid)
{
throw new AppException("搜索失败: " + searchResponse.DebugInformation);
}
return (searchResponse.Total, searchResponse.Documents.ToList());
}
/// <summary>
/// ============ 6. 统计文档数 ============
/// </summary>
public async Task<long> CountDocumentsAsync()
{
var countResponse = await _client.CountAsync<GoodsSearchDocument>(c => c
.Index(_indexName)
.RequestConfiguration(r => r.RequestTimeout(QueryTimeout))
);
if (countResponse.IsValid)
{
Console.WriteLine($"索引 [{_indexName}] 当前文档总数: {countResponse.Count}");
return countResponse.Count;
}
else
{
Console.WriteLine("统计失败: " + countResponse.DebugInformation);
throw new AppException(countResponse.DebugInformation);
}
}
/// <summary>
/// ============ 7. 查询 OpenSearch 状态 ============
/// </summary>
public async Task<OpenSearchStatusDto> GetStatusAsync()
{
var stopwatch = Stopwatch.StartNew();
var status = new OpenSearchStatusDto
{
NodeUrl = _nodeUrl,
IndexName = _indexName,
};
try
{
var ping = await _client.PingAsync(p => p
.RequestConfiguration(r => r.RequestTimeout(QueryTimeout)));
status.Connected = ping.IsValid;
if (!ping.IsValid)
{
status.Message = ping.DebugInformation;
_logger.LogError(ping.DebugInformation);
return status;
}
_logger.LogInformation("OpenSerach 已连接");
var clusterHealth = await _client.Cluster.HealthAsync(Indices.All, h => h
.RequestConfiguration(r => r.RequestTimeout(QueryTimeout)));
if (!clusterHealth.IsValid)
{
status.Message = clusterHealth.DebugInformation;
return status;
}
status.ClusterName = clusterHealth.ClusterName;
status.ClusterStatus = clusterHealth.Status.ToString().ToLowerInvariant();
status.NumberOfNodes = clusterHealth.NumberOfNodes;
status.NumberOfDataNodes = clusterHealth.NumberOfDataNodes;
status.ActivePrimaryShards = clusterHealth.ActivePrimaryShards;
status.ActiveShards = clusterHealth.ActiveShards;
status.RelocatingShards = clusterHealth.RelocatingShards;
status.InitializingShards = clusterHealth.InitializingShards;
status.UnassignedShards = clusterHealth.UnassignedShards;
status.IndexExists = await IndexExistsAsync();
if (status.IndexExists)
{
var mappingStatus = await GetIndexMappingStatusAsync();
status.MappingHealthy = mappingStatus.Healthy;
status.IndexAnalyzer = mappingStatus.IndexAnalyzer;
status.SearchAnalyzer = mappingStatus.SearchAnalyzer;
var count = await _client.CountAsync<GoodsSearchDocument>(c => c
.Index(_indexName)
.RequestConfiguration(r => r.RequestTimeout(QueryTimeout)));
status.DocumentCount = count.IsValid ? count.Count : -1;
if (!count.IsValid)
{
status.Message = count.DebugInformation;
}
}
else
{
status.Message = $"索引 [{_indexName}] 不存在";
}
status.Healthy = status.IndexExists
&& status.MappingHealthy
&& status.ClusterStatus != "red"
&& status.DocumentCount >= 0;
}
catch (Exception ex)
{
status.Healthy = false;
status.Message = ex.Message;
}
finally
{
stopwatch.Stop();
status.ElapsedMilliseconds = stopwatch.ElapsedMilliseconds;
}
return status;
}
/// <summary>
/// 清空索引:删除后按统一映射重建,重建期间该索引不可查(由后台定时任务负责回填数据,接受短暂空窗)
/// </summary>
public async Task<bool> ClearIndexAsync()
{
var existsResponse = await _client.Indices.ExistsAsync(_indexName, d => d
.RequestConfiguration(r => r.RequestTimeout(QueryTimeout)));
if (!existsResponse.Exists)
{
Console.WriteLine($"索引 {_indexName} 不存在");
return false;
}
var deleteResponse = await _client.Indices.DeleteAsync(_indexName, d => d
.RequestConfiguration(r => r.RequestTimeout(AdminTimeout)));
if (!deleteResponse.IsValid)
{
Console.WriteLine($"删除索引 {_indexName} 失败: {deleteResponse.DebugInformation}");
return false;
}
Console.WriteLine($"索引 {_indexName} 已删除");
return await CreateIndexAsync();
}
}
}
@@ -0,0 +1,82 @@
using MAX.Core.DependencyInjection;
using Microsoft.Extensions.Configuration;
using System.IO.Compression;
using System.Text;
namespace Store.Modules.CloudProduct.Services
{
/// <summary>
/// 商品原始数据文件存储:按 goodsId % 100 分目录,文件名即商品ID,GZip 压缩保存。
/// </summary>
public interface IRawDataStorage : IScopedDependency
{
/// <summary>
/// 保存原始数据,返回保存后的完整路径。
/// </summary>
Task<string> SaveAsync(long goodsId, string rawData);
/// <summary>
/// 读取并解压原始数据;文件不存在时返回 null。
/// </summary>
Task<string?> ReadAsync(long goodsId);
/// <summary>
/// 判断指定商品的原始数据文件是否存在。
/// </summary>
bool Exists(long goodsId);
}
internal class RawDataStorage : IRawDataStorage
{
private readonly string _rootPath;
public RawDataStorage(IConfiguration configuration)
{
var configured = configuration.GetValue<string>("RawData:Path");
if (string.IsNullOrWhiteSpace(configured))
configured = "RawData";
_rootPath = Path.GetFullPath(configured);
}
/// <inheritdoc />
public async Task<string> SaveAsync(long goodsId, string rawData)
{
var filePath = GetFilePath(goodsId);
var dir = Path.GetDirectoryName(filePath)!;
Directory.CreateDirectory(dir);
await using var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None);
await using var gzip = new GZipStream(fileStream, CompressionLevel.Fastest);
await using var writer = new StreamWriter(gzip, new UTF8Encoding(false));
await writer.WriteAsync(rawData);
return filePath;
}
/// <inheritdoc />
public async Task<string?> ReadAsync(long goodsId)
{
var filePath = GetFilePath(goodsId);
if (!File.Exists(filePath))
return null;
await using var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
await using var gzip = new GZipStream(fileStream, CompressionMode.Decompress);
using var reader = new StreamReader(gzip, new UTF8Encoding(false));
return await reader.ReadToEndAsync();
}
/// <inheritdoc />
public bool Exists(long goodsId)
{
return File.Exists(GetFilePath(goodsId));
}
private string GetFilePath(long goodsId)
{
var subDir = (goodsId % 100).ToString();
return Path.Combine(_rootPath, subDir, goodsId.ToString());
}
}
}
+49
View File
@@ -0,0 +1,49 @@
using MAX.Core.DependencyInjection;
using MAX.Core.Interfaces;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Store.Modules.CloudProduct.Services;
using System.ComponentModel;
namespace Store.Modules.CloudProduct
{
public class Startup : IStartup
{
public int Priority => IntPriority.Normal;
public void Initialize()
{
}
public void Register(IServiceRegistrar registrar)
{
Func<IServiceProvider, IFreeSql> KJDFsqlFactory = r =>
{
var config = r.GetRequiredService<IConfiguration>();
var connection = config.GetValue<string>("CloudProductConnection");
IFreeSql fsql = new FreeSql.FreeSqlBuilder()
.UseConnectionString(FreeSql.DataType.MySql, connection)
.UseAdoConnectionPool(true)
.Build();
return fsql;
};
registrar.RegisterSingleton<IFreeSql>("CloudProductConnection", (s, k) =>
{
return KJDFsqlFactory(s);
});
}
public async void Start(IServiceProvider serviceProvider)
{
var openSearchService = serviceProvider.GetRequiredService<OpenSearchService>();
await openSearchService.GetStatusAsync();
}
}
}
@@ -0,0 +1,26 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\Store.Framework\Store.Framework.csproj" />
</ItemGroup>
<ItemGroup>
<!-- 本模块自己的配置文件:源码里叫 appsettings.json,构建后复制到宿主输出目录时改名为
appsettings.CloudProduct.json,避免和宿主自己的 appsettings.json 互相覆盖。
由 builder.AddStoreHub() 自动并入宿主配置树(在 appsettings*.json 之后、环境变量之前)。 -->
<None Update="appsettings.json" Link="appsettings.CloudProduct.json" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Hangfire.AspNetCore" Version="1.8.25" />
<PackageReference Include="Hangfire.Dashboard.Basic.Authentication" Version="8.0.0" />
<PackageReference Include="Hangfire.MySqlStorage" Version="2.0.3" />
<PackageReference Include="OpenSearch.Client" Version="2.1.0" />
</ItemGroup>
</Project>
+18
View File
@@ -0,0 +1,18 @@
{
"CloudProductConnection": "Server=192.168.0.200;Port=3306;Database=goods_center;Uid=root;Pwd=123456;Allow User Variables=true",
"Search": {
"Url": "http://192.168.0.200:9200",
"IndexName": "goods_search"
},
"RawData": {
"Path": "E:\\GoodsRawData"
},
"Indexing": {
"Mode": "Background",
"Cron": "*/5 * * * *",
"BatchSize": 20000
},
"Delete": {
"SoftDelete": true
}
}
@@ -1,27 +1,25 @@
using Asp.Versioning;
using MAX.Framework.Dtos;
using MAX.Framework.Security;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using StoreHub.Framework.Commons;
using StoreHub.Framework.Security;
using StoreHub.Services;
using StoreHub.Services.Dtos;
using System.Security.Claims;
namespace StoreHub.Controllers
namespace Store.Api.Controllers
{
[ApiController]
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/[controller]/[action]")]
public class AuthController : ControllerBase
{
private readonly IUserService _userService;
//private readonly IUserService _userService;
private readonly ITokenService _tokenService;
private readonly ICurrentUser _currentUser;
private readonly IOnlineUserStore _onlineUserStore;
public AuthController(IUserService userService, ITokenService tokenService, ICurrentUser currentUser, IOnlineUserStore onlineUserStore)
public AuthController( ITokenService tokenService, ICurrentUser currentUser, IOnlineUserStore onlineUserStore)
{
_userService = userService;
//_userService = userService;
_tokenService = tokenService;
_currentUser = currentUser;
_onlineUserStore = onlineUserStore;
@@ -36,24 +34,23 @@ namespace StoreHub.Controllers
{
if (request is null || string.IsNullOrWhiteSpace(request.UserName) || string.IsNullOrWhiteSpace(request.Password))
{
return ApiResult.Error("用户名或密码不能为空", 400);
return ApiResult.Fail("用户名或密码不能为空", 400);
}
UserDto? user = await _userService.LoginAsync(request.UserName, request.Password);
if (user is null)
{
return ApiResult.Error("用户名或密码错误", 401);
}
//UserDto? user = await _userService.LoginAsync(request.UserName, request.Password);
//if (user is null)
//{
// return ApiResult.Error("用户名或密码错误", 401);
//}
var claims = new List<Claim>
{
new(JwtClaimTypes.UserId, user.Id.ToString()),
new(JwtClaimTypes.UserName, user.UserName),
new(JwtClaimTypes.NickName, user.NickName),
};
//var claims = new List<Claim>
//{
// new(JwtClaimTypes.UserName, user.UserName),
// new(JwtClaimTypes.NickName, user.NickName),
//};
TokenResult token = _tokenService.CreateToken(claims);
return ApiResult.Success<object?>(token);
//TokenResult token = _tokenService.CreateToken(claims);
return ApiResult<object?>.Success(111);
}
/// <summary>
@@ -63,12 +60,12 @@ namespace StoreHub.Controllers
[Authorize]
public ApiResult<object?> Logout()
{
if (_currentUser.Id is int userId)
if (_currentUser.UserName is string username)
{
_onlineUserStore.SignOut(userId);
_onlineUserStore.SignOut(username);
}
return ApiResult.Success<object?>(null);
return ApiResult<object?>.Success(null);
}
/// <summary>
@@ -78,9 +75,8 @@ namespace StoreHub.Controllers
[Authorize]
public ApiResult<object?> Me()
{
return ApiResult.Success<object?>(new
return ApiResult<object?>.Success(new
{
UserId = _currentUser.Id,
UserName = _currentUser.UserName,
NickName = _currentUser.NickName,
});
@@ -94,7 +90,7 @@ namespace StoreHub.Controllers
public ApiResult<object?> OnlineUsers()
{
IReadOnlyList<OnlineUserInfo> users = _onlineUserStore.GetOnlineUsers();
return ApiResult.Success<object?>(new
return ApiResult<object?>.Success(new
{
Count = users.Count,
Users = users,
@@ -1,16 +1,15 @@
using Asp.Versioning;
using Microsoft.AspNetCore.Mvc;
using StoreHub.Framework.Repositorys;
using Store.Framework.Repositorys;
using System.ComponentModel;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace StoreHub.Controllers
namespace Store.Api.Controllers
{
[ApiController]
[Description("测试温度")]
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/[controller]")]
[ApiVersionNeutral]
[Route("wxxd_user/[action]")]
public class UserController : ControllerBase
{
private readonly IUserRepository _userRepository;
@@ -1,9 +1,10 @@
using Asp.Versioning;
using MAX.Framework.Dtos;
using Microsoft.AspNetCore.Mvc;
using StoreHub.Framework.Commons;
using Store.Api;
using System.ComponentModel;
namespace StoreHub.Controllers
namespace Store.Api.Controllers
{
[ApiController]
[Description("测试温度")]
@@ -17,7 +18,7 @@ namespace StoreHub.Controllers
];
[HttpGet(Name = "GetWeatherForecast")]
public ApiResult<IEnumerable<WeatherForecast>> Get()
public IEnumerable<WeatherForecast> Get()
{
IEnumerable<WeatherForecast> data = Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
@@ -27,7 +28,7 @@ namespace StoreHub.Controllers
})
.ToArray();
return ApiResult.Success(data);
return data;
}
}
}
@@ -1,8 +1,9 @@
using Asp.Versioning;
using MAX.Framework.Dtos;
using Microsoft.AspNetCore.Mvc;
using StoreHub.Framework.Commons;
using Store.Api;
namespace StoreHub.Controllers.v2
namespace Store.Api.Controllers.v2
{
[ApiController]
[ApiVersion("2.0")]
@@ -26,7 +27,7 @@ namespace StoreHub.Controllers.v2
})
.ToArray();
return ApiResult.Success(data);
return ApiResult<IEnumerable<WeatherForecastV2>>.Success(data);
}
}
}
+19 -12
View File
@@ -1,6 +1,6 @@
using Asp.Versioning;
using Asp.Versioning;
using MAX.Framework.DependencyInjection;
using Scalar.AspNetCore;
using StoreHub.Framework.DependencyInjection;
public partial class Program
{
@@ -8,13 +8,19 @@ public partial class Program
{
var builder = WebApplication.CreateBuilder(args);
// IOC 注册:自动注册 ISingletonDependency / IScopedDependency / ITransientDependency,并执行所有 IStartup(实现见 StoreHub.Framework)
builder.Services.AddStoreHub();
// IOC 注册:自动注册 ISingletonDependency / IScopedDependency / ITransientDependency,并执行所有 IStartup / IModule.AddModule
// 模块服务注册阶段(等价于 builder.Services.AddStoreHub(builder.Configuration, builder.Environment),额外把配置/环境交给模块)
builder.AddStore();
builder.Services.AddFreeSqlDB();
// JWT 验证:注册 JwtBearer 认证 + 令牌服务 + OpenAPI Bearer 安全方案(配置节 Jwt)
builder.Services.AddStoreHubJwt(builder.Configuration);
// Add services to the container.
//builder.Services.Configure<Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServerOptions>(options =>
//{
// // 兼容迁移的同步控制器:允许同步读写请求/响应 IO(旧 asmx 行为)
// options.AllowSynchronousIO = true;
//});
builder.Services.AddControllers();
// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
builder.Services.AddApiVersioning(options =>
@@ -28,14 +34,12 @@ public partial class Program
options.SubstituteApiVersionInUrl = true;
}).AddOpenApi();
#region DB
#endregion
var app = builder.Build();
WebApplication app = builder.Build();
app.UseStore();
// 初始化 KJD 迁移的静态提供者(MysqlUtils 连接提供 / 业务配置读取)
//StoreHub.KJDWebService.Commons.AdoProvider.SetServiceProvider(app.Services);
//StoreHub.KJDWebService.Commons.KJDConfig.SetConfiguration(app.Configuration);
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
@@ -59,4 +63,7 @@ public partial class Program
app.Run();
}
}
}
@@ -6,7 +6,7 @@
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "scalar/v1",
"applicationUrl": "http://localhost:5295",
"applicationUrl": "http://localhost:9000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
@@ -16,7 +16,7 @@
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "scalar/v1",
"applicationUrl": "https://localhost:7241;http://localhost:5295",
"applicationUrl": "https://localhost:7241;http://localhost:9000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
@@ -5,6 +5,13 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<Compile Remove="Log\**" />
<Content Remove="Log\**" />
<EmbeddedResource Remove="Log\**" />
<None Remove="Log\**" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.10" />
@@ -12,9 +19,8 @@
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\StoreHub.Framework\StoreHub.Framework.csproj" />
<ProjectReference Include="..\StoreHub.KJDWebService\StoreHub.KJDWebService.csproj" />
<ProjectReference Include="..\StoreHub.Services\StoreHub.Services.csproj" />
<ProjectReference Include="..\Models\CloudProduct\Store.Modules.CloudProduct.csproj" />
<ProjectReference Include="..\Store.Framework\Store.Framework.csproj" />
</ItemGroup>
</Project>
File renamed without changes.
@@ -1,4 +1,4 @@
namespace StoreHub
namespace Store.Api
{
public class WeatherForecast
{
@@ -1,4 +1,4 @@
namespace StoreHub
namespace Store.Api
{
public class WeatherForecastV2
{
File renamed without changes.
+47
View File
@@ -0,0 +1,47 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"ConnectionStrings": {
"DefaultConnection": "Server=192.168.0.200;Port=3306;Database=mysql;Uid=root;Pwd=123456;",
"KJDConnection": "Server=192.168.0.200;Port=3306;Database=mysql;Uid=root;Pwd=123456;",
"ConnKJD": "Server=192.168.0.200;Port=3306;Database=mysql;Uid=root;Pwd=123456;"
//"KJDConnection": "Max Pool Size=512;Database='kjd';Data Source='nj-cynosdbmysql-grp-hl51pkfr.sql.tencentcdb.com';Port=27660;User Id='kjd';Password='Temukjd0625';Charset=utf8mb4;",
//"KJDBAKConnection": "Max Pool Size=512;Database='kjd';Data Source='nj-cynosdbmysql-grp-9s7x16mt.sql.tencentcdb.com';Port=24049;User Id='kjdbak';Password='Temukjd0126';Charset=utf8mb4;",
//"ConnKJD": "Max Pool Size=512;Database='kjd';Data Source='nj-cynosdbmysql-grp-hl51pkfr.sql.tencentcdb.com';Port=27660;User Id='kjd';Password='Temukjd0625';Charset=utf8mb4;",
//"ConnKJDBAK": "Max Pool Size=512;Database='kjd';Data Source='nj-cynosdbmysql-grp-9s7x16mt.sql.tencentcdb.com';Port=24049;User Id='kjdbak';Password='Temukjd0126';Charset=utf8mb4;"
},
"KJDConfig": {
"UpdateVersion": "525",
"UpdateFileDir": "C:\\inetpub\\wwwroot\\kjd_update",
"UpdateNewUrl": "http://weidian.e57.cn/kjd_update/",
"UpdateExe": "http://1.13.195.131:9000/Download/Update.exe",
"UpdateExeChk": "CE4A009B7AA330314F03EEA0C3AB23F9",
"LowVersion": "523",
"LimitVersion": "823",
"GetReturnPackage": "true",
"GetWXRecommendHotProd": "true",
"GetWXRecommendHotProdOncePerDay": "false",
"GetWXRecommendHotProdMinViewUv": "200",
"GetWXRecommendHotProdInterval": "3",
"IsKeepBase64UploadImgFile": "0",
"UpdateWxFindOrderFileDir": "C:\\inetpub\\wwwroot\\find_order_update",
"UpdateWxFindOrderUrl": "http://weidian.e57.cn/find_order_update/",
"WxFindOrderLimitVersion": "172",
"WxFindOrderLowVersion": "99"
},
"Jwt": {
"Issuer": "StoreHub",
"Audience": "StoreHub.Client",
"SigningKey": "StoreHub--Smxf8DtV8a5dFdaCVCXtFfWbmMRfw53ectEjr8JvhUjGpPP7fuBdRn",
"ExpiresMinutes": 2880,
"ClockSkewMinutes": 5,
"ValidateIssuer": true,
"ValidateAudience": true,
"ValidateLifetime": true
},
"AllowedHosts": "*"
}
+16
View File
@@ -0,0 +1,16 @@
<Solution>
<Folder Name="/Core/">
<Project Path="Core/MAX.Core/MAX.Core.csproj" />
<Project Path="Core/MAX.Framework/MAX.Framework.csproj" />
</Folder>
<Folder Name="/Modules/">
<Project Path="Models/CloudProduct/Store.Modules.CloudProduct.csproj" Id="9720597a-661b-47d8-90c7-83e17c6d5920" />
</Folder>
<Folder Name="/_SolutionItems/">
<File Path="Directory.Build.props" />
</Folder>
<Project Path="Store.API/Store.Api.csproj" />
<Project Path="Store.Framework/Store.Framework.csproj" />
<Project Path="StoreHub.KJDWebService/StoreHub.KJDWebService.csproj" />
<Project Path="StoreHub.Services/Store.Services.csproj" />
</Solution>
+12
View File
@@ -0,0 +1,12 @@
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Text;
namespace Store.Framework.Base
{
[ApiController]
public class AppControllerBase : ControllerBase
{
}
}
@@ -3,7 +3,7 @@ using System;
using System.Collections.Generic;
using System.Text;
namespace StoreHub.Framework.Models
namespace Store.Framework.Models
{
/// <summary>
/// 用户实体
@@ -1,12 +1,12 @@
using FreeSql;
using MAX.Core.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using StoreHub.Framework.Models;
using Store.Framework.Models;
using System;
using System.Collections.Generic;
using System.Text;
namespace StoreHub.Framework.Repositorys
namespace Store.Framework.Repositorys
{
public interface IUserRepository : IBaseRepository<User>
{
@@ -1,11 +1,10 @@
using FreeSql;
using MAX.Core.DependencyInjection;
using MAX.Core.Infrastructure;
using MAX.Core.Interfaces;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using StoreHub.Framework.Repositorys;
namespace StoreHub.Framework
namespace Store.Framework
{
public class Startup : IStartup
{
@@ -18,20 +17,21 @@ namespace StoreHub.Framework
public void Register(IServiceRegistrar registrar)
{
Func<IServiceProvider, IFreeSql> userFsqlFactory = r =>
{
var config = r.GetRequiredService<IConfiguration>();
var connection = config.GetConnectionString("UserConnection");
IFreeSql fsql = new FreeSql.FreeSqlBuilder()
.UseConnectionString(FreeSql.DataType.MySql, connection)
.UseAdoConnectionPool(true)
.Build();
return fsql;
};
registrar.RegisterSingleton<IFreeSql>("UserDB", (s, k) =>
{
return userFsqlFactory(s);
});
//Func<IServiceProvider, IFreeSql> userFsqlFactory = r =>
//{
// var config = r.GetRequiredService<IConfiguration>();
// var connection = config.GetConnectionString("UserConnection");
// IFreeSql fsql = new FreeSql.FreeSqlBuilder()
// .UseConnectionString(FreeSql.DataType.MySql, connection)
// .UseAdoConnectionPool(true)
// .Build();
// return fsql;
//};
//registrar.RegisterSingleton<IFreeSql>("UserDB", (s, k) =>
//{
// return userFsqlFactory(s);
//});
Func<IServiceProvider, IFreeSql> KJDFsqlFactory = r =>
@@ -49,5 +49,11 @@ namespace StoreHub.Framework
return KJDFsqlFactory(s);
});
}
public void Start(IServiceProvider serviceProvider)
{
}
}
}
+20
View File
@@ -0,0 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Core\MAX.Core\MAX.Core.csproj" />
<ProjectReference Include="..\Core\MAX.Framework\MAX.Framework.csproj" />
</ItemGroup>
<ItemGroup>
</ItemGroup>
</Project>
+53
View File
@@ -0,0 +1,53 @@
using StoreHub.KJDWebService.Commons;
using System;
using System.Collections.Generic;
using System.Linq;
namespace StoreHub.KJDWebService.Commons
{
public class BaseClass
{
public static string BuildPDDObjString(string file, bool IsLoginDef = false)
{
string LoginApiUrl = "http://1.13.195.131:9001";
string MainPath = "kuajingda";
return LoginApiUrl + "/bxx_" + file + "?obj=" + MainPath + "/bxx_" + file;
}
public static int TimeDifferent = 0;
public static int VersionCount = 99999999;
public static int CompanyId = 1;
public static string CompanyName = "1";
public static string UserKey = "1";
public static string Mobile = "18888888888";
public static string UserName = "18888888888";
public static string ShopId = "18888888888";
public static string ShopName = "18888888888";
}
public class UserLogin
{
/// <summary>
/// 获取签名字符串,新版
/// </summary>
/// <returns></returns>
public static string GetSignaturex()
{
return GetSignaturex(BaseClass.ShopId, BaseClass.ShopName);
}
public static string GetSignaturex(string shopId, string shopName)
{
if (string.IsNullOrEmpty(shopId))
shopId = "11111111";
if (string.IsNullOrEmpty(shopName))
shopName = "wx11111111";
int time = TimeUtils.DateTimeToTimestampSeconds(DateTime.Now) + BaseClass.TimeDifferent;
string time1 = EncrypUtil.Encryption(time);
return "time=" + time + "&code=" + time1 + "&NbCodeVersion=1" + "&version=" + BaseClass.VersionCount +
"&company_id=" + BaseClass.CompanyId + "&company=" + HtmlUtils.UrlEncodeUtf8(BaseClass.CompanyName) +
"&user_name=" + BaseClass.UserName + "&user_key=" + BaseClass.UserKey + "&mobile=" + BaseClass.Mobile +
"&sid=" + shopId + "&shop=" + HtmlUtils.UrlEncodeUtf8(shopName);
}
}
}
+60
View File
@@ -0,0 +1,60 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
namespace StoreHub.KJDWebService.Commons
{
public class EncrypUtil
{
/// <summary>
/// 加密算法
/// </summary>
/// <param name="s">加密字符串</param>
/// <returns></returns>
public static string Encryption(int s)
{
string sign = $"{s}sdhewu*/fhAAue48485ew5+5%@3485esGFFHFD";
return GetMd5(sign);
}
/// <summary>
/// MD5加密
/// </summary>
/// <param name="instring"></param>
/// <returns></returns>
public static string GetMd5(string instring)
{
byte[] result = Encoding.Default.GetBytes(instring.Trim());
MD5 md5 = new MD5CryptoServiceProvider();
byte[] output = md5.ComputeHash(result);
return BitConverter.ToString(output).Replace("-", "");
}
/// <summary>
/// 获取文件MD5值
/// </summary>
/// <param name="FilePath"></param>
/// <returns></returns>
public static string GetFileMd5(string FilePath)
{
try
{
FileStream get_file = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.Read);
System.Security.Cryptography.MD5CryptoServiceProvider get_md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] hash_byte = get_md5.ComputeHash(get_file);
string resule = System.BitConverter.ToString(hash_byte);
resule = resule.Replace("-", "");
get_file.Close();
return resule;
}
catch (Exception e)
{
return e.ToString();
}
}
}
}
@@ -0,0 +1,705 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
using NaiBa.Util.Helper;
using Newtonsoft.Json;
namespace NaiBa.Util.Extension
{
public static partial class Extensions
{
#region 转换为long
/// <summary>
/// 将object转换为long,若转换失败,则返回0。不抛出异常。
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static long ParseToLong(this object obj)
{
if (obj == null)
return 0L;
try
{
string str = obj.ParseToString();
if (string.IsNullOrEmpty(str))
{
return 0;
}
return long.Parse(str);
}
catch
{
return 0L;
}
}
public static long? ParseToNullableLong(this object obj)
{
if (obj == null)
return null;
try
{
string str = obj.ParseToString();
if (string.IsNullOrEmpty(str))
{
return null;
}
return long.Parse(str);
}
catch
{
return null;
}
}
/// <summary>
/// 将object转换为long,若转换失败,则返回指定值。不抛出异常。
/// </summary>
/// <param name="str"></param>
/// <param name="defaultValue"></param>
/// <returns></returns>
public static long ParseToLong(this string str, long defaultValue)
{
if (str == null)
return defaultValue;
try
{
return long.Parse(str);
}
catch
{
return defaultValue;
}
}
#endregion
#region 转换为int
/// <summary>
/// 将object转换为int,若转换失败,则返回0。不抛出异常。
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static int ParseToInt(this object str)
{
if (str == null)
return 0;
try
{
return Convert.ToInt32(str);
}
catch
{
return 0;
}
}
public static int? ParseToNullableInt(this object str)
{
if (str == null)
return null;
try
{
return Convert.ToInt32(str);
}
catch
{
return null;
}
}
public static int DecimalPointParseToInt(this object str)
{
try
{
string temp = str.ParseToString();
int i = temp.IndexOf('.');
if (i > 0)
{
temp = temp.Substring(0, i);
}
return Convert.ToInt32(temp);
}
catch
{
return 0;
}
}
/// <summary>
/// 将object转换为int,若转换失败,则返回指定值。不抛出异常。
/// null返回默认值
/// </summary>
/// <param name="str"></param>
/// <param name="defaultValue"></param>
/// <returns></returns>
public static int ParseToInt(this object str, int defaultValue)
{
if (str == null)
{
return defaultValue;
}
try
{
return Convert.ToInt32(str);
}
catch
{
return defaultValue;
}
}
#endregion
#region 转换为short
/// <summary>
/// 将object转换为short,若转换失败,则返回0。不抛出异常。
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static short ParseToShort(this object obj)
{
try
{
return short.Parse(obj.ToString());
}
catch
{
return 0;
}
}
/// <summary>
/// 将object转换为short,若转换失败,则返回指定值。不抛出异常。
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static short ParseToShort(this object str, short defaultValue)
{
try
{
return short.Parse(str.ToString());
}
catch
{
return defaultValue;
}
}
#endregion
#region 转换为demical
/// <summary>
/// 将object转换为demical,若转换失败,则返回指定值。不抛出异常。
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static decimal ParseToDecimal(this object str, decimal defaultValue)
{
try
{
return decimal.Parse(str.ToString());
}
catch
{
return defaultValue;
}
}
/// <summary>
/// 将object转换为demical,若转换失败,则返回0。不抛出异常。
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static decimal ParseToDecimal(this object str)
{
try
{
return decimal.Parse(str.ToString());
}
catch
{
return 0;
}
}
public static decimal? ParseToNullableDecimal(this object str)
{
try
{
return decimal.Parse(str.ToString());
}
catch
{
return null;
}
}
#endregion
#region 转化为bool
/// <summary>
/// 将object转换为bool,若转换失败,则返回false。不抛出异常。
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static bool ParseToBool(this object str)
{
try
{
if (str is null)
return false;
return bool.Parse(str.ToString());
}
catch
{
return false;
}
}
/// <summary>
/// 将object转换为bool,若转换失败,则返回指定值。不抛出异常。
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static bool ParseToBool(this object str, bool result)
{
try
{
return bool.Parse(str.ToString());
}
catch
{
return result;
}
}
#endregion
#region 转换为float
/// <summary>
/// 将object转换为float,若转换失败,则返回0。不抛出异常。
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static float ParseToFloat(this object str)
{
try
{
return float.Parse(str.ToString());
}
catch
{
return 0;
}
}
/// <summary>
/// 将object转换为float,若转换失败,则返回指定值。不抛出异常。
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static float ParseToFloat(this object str, float result)
{
try
{
return float.Parse(str.ToString());
}
catch
{
return result;
}
}
#endregion
#region 转换为Guid
/// <summary>
/// 将string转换为Guid,若转换失败,则返回Guid.Empty。不抛出异常。
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static Guid ParseToGuid(this string str)
{
try
{
return new Guid(str);
}
catch
{
return Guid.Empty;
}
}
#endregion
#region 转换为DateTime
public static DateTime? ParseToDateTimeNullable(this string str)
{
try
{
if (string.IsNullOrWhiteSpace(str))
{
return null;
}
try
{
return DateTime.Parse(str);
}
catch
{
}
if (str.Contains("年") && str.Contains("月") && str.Contains("日") && !str.Contains("周"))
str = str.Replace("年", "-").Replace("月", "-").Replace("日", "").Replace("时", ":").Replace("分", ":").Replace("秒", "").Trim(' ', ':');
if (str.Contains("-") || str.Contains("/"))
{
return DateTime.Parse(str);
}
else
{
int length = str.Length;
switch (length)
{
case 4:
return DateTime.ParseExact(str, "yyyy", System.Globalization.CultureInfo.CurrentCulture);
case 6:
return DateTime.ParseExact(str, "yyyyMM", System.Globalization.CultureInfo.CurrentCulture);
case 8:
return DateTime.ParseExact(str, "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture);
case 10:
return DateTime.ParseExact(str, "yyyyMMddHH", System.Globalization.CultureInfo.CurrentCulture);
case 12:
return DateTime.ParseExact(str, "yyyyMMddHHmm", System.Globalization.CultureInfo.CurrentCulture);
case 14:
return DateTime.ParseExact(str, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture);
default:
return DateTime.ParseExact(str, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture);
}
}
}
catch
{
return null;
}
}
/// <summary>
/// 将string转换为DateTime,若转换失败,则返回日期最小值。不抛出异常。
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static DateTime ParseToDateTime(this string str)
{
try
{
if (string.IsNullOrWhiteSpace(str))
{
return DateTime.MinValue;
}
if (str.Contains("-") || str.Contains("/"))
{
return DateTime.Parse(str);
}
else
{
int length = str.Length;
switch (length)
{
case 4:
return DateTime.ParseExact(str, "yyyy", System.Globalization.CultureInfo.CurrentCulture);
case 6:
return DateTime.ParseExact(str, "yyyyMM", System.Globalization.CultureInfo.CurrentCulture);
case 8:
return DateTime.ParseExact(str, "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture);
case 10:
return DateTime.ParseExact(str, "yyyyMMddHH", System.Globalization.CultureInfo.CurrentCulture);
case 12:
return DateTime.ParseExact(str, "yyyyMMddHHmm", System.Globalization.CultureInfo.CurrentCulture);
case 14:
return DateTime.ParseExact(str, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture);
default:
return DateTime.ParseExact(str, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture);
}
}
}
catch
{
return DateTime.MinValue;
}
}
/// <summary>
/// 将string转换为DateTime,若转换失败,则返回默认值。
/// </summary>
/// <param name="str"></param>
/// <param name="defaultValue"></param>
/// <returns></returns>
public static DateTime ParseToDateTime(this string str, DateTime? defaultValue)
{
try
{
if (string.IsNullOrWhiteSpace(str))
{
return defaultValue.GetValueOrDefault();
}
if (str.Contains("-") || str.Contains("/"))
{
return DateTime.Parse(str);
}
else
{
int length = str.Length;
switch (length)
{
case 4:
return DateTime.ParseExact(str, "yyyy", System.Globalization.CultureInfo.CurrentCulture);
case 6:
return DateTime.ParseExact(str, "yyyyMM", System.Globalization.CultureInfo.CurrentCulture);
case 8:
return DateTime.ParseExact(str, "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture);
case 10:
return DateTime.ParseExact(str, "yyyyMMddHH", System.Globalization.CultureInfo.CurrentCulture);
case 12:
return DateTime.ParseExact(str, "yyyyMMddHHmm", System.Globalization.CultureInfo.CurrentCulture);
case 14:
return DateTime.ParseExact(str, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture);
default:
return DateTime.ParseExact(str, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture);
}
}
}
catch
{
return defaultValue.GetValueOrDefault();
}
}
#endregion
#region 转换为string
/// <summary>
/// 将object转换为string,若转换失败,则返回""。不抛出异常。
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string ParseToString(this object obj)
{
try
{
if (obj == null)
{
return string.Empty;
}
else
{
if (obj is DateTime)
return (obj as DateTime?).Value.ToString("yyyy-MM-dd HH:mm:ss");
return obj.ToString();
}
}
catch
{
return string.Empty;
}
}
public static string ParseToNullableString(this object obj)
{
try
{
if (obj == null)
{
return null;
}
else
{
if (obj is DateTime)
return (obj as DateTime?).Value.ToString("yyyy-MM-dd HH:mm:ss");
return obj.ToString();
}
}
catch
{
return null;
}
}
public static string ParseToStrings<T>(this object obj, string split = ",")
{
try
{
var list = obj as IEnumerable<T>;
if (list != null)
{
return string.Join(split, list);
}
else
{
return obj.ToString();
}
}
catch
{
return string.Empty;
}
}
#endregion
#region 转换为double
/// <summary>
/// 将object转换为double,若转换失败,则返回0。不抛出异常。
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static double ParseToDouble(this object obj)
{
try
{
return double.Parse(obj.ToString());
}
catch
{
return 0;
}
}
/// <summary>
/// 将object转换为double,若转换失败,则返回指定值。不抛出异常。
/// </summary>
/// <param name="str"></param>
/// <param name="defaultValue"></param>
/// <returns></returns>
public static double ParseToDouble(this object str, double defaultValue)
{
try
{
return double.Parse(str.ToString());
}
catch
{
return defaultValue;
}
}
#endregion
#region 字符串转指定类型Array
public static T[] SplitToArray<T>(this string value, string split = ",")
{
if (string.IsNullOrEmpty(value))
{
return default(T[]);
}
var arr = value.Split(new string[] { split }, StringSplitOptions.RemoveEmptyEntries).CastSuper<T>().ToArray();
return arr;
}
public static T[] SplitToArray<T>(this string value, string[] split)
{
if (string.IsNullOrEmpty(value))
{
return default(T[]);
}
var arr = value.Split(split, StringSplitOptions.RemoveEmptyEntries).CastSuper<T>().ToArray();
return arr;
}
#endregion
#region 字符串转指定类型List
public static List<T> SplitToList<T>(this string value, string split = ",")
{
if (string.IsNullOrEmpty(value))
{
return new List<T>();
}
var list = value.Split(new string[] { split }, StringSplitOptions.RemoveEmptyEntries).CastSuper<T>().ToList();
return list;
}
public static List<T> SplitToList<T>(this string value, string[] split)
{
if (string.IsNullOrEmpty(value))
{
return new List<T>();
}
var list = value.Split(split, StringSplitOptions.RemoveEmptyEntries).CastSuper<T>().ToList();
return list;
}
#endregion
#region 强制转换类型
/// <summary>
/// 强制转换类型
/// </summary>
/// <typeparam name="TResult"></typeparam>
/// <param name="source"></param>
/// <returns></returns>
public static IEnumerable<TResult> CastSuper<TResult>(this IEnumerable source)
{
foreach (object item in source)
{
yield return (TResult)Convert.ChangeType(item, typeof(TResult));
}
}
#endregion
#region Object转换为Json
public static string ParseToJson(this object obj)
{
return JsonConvert.SerializeObject(obj);
}
#endregion
#region Json转为Object
public static T ParseToObject<T>(this string json)
{
if (string.IsNullOrEmpty(json))
{
return Activator.CreateInstance<T>();
}
return JsonConvert.DeserializeObject<T>(json);
}
#endregion
#region 深拷贝(克隆出一个新对象,拷贝对象里面的数据和子对象)
public static T DeepClone<T>(this T o)
{
return o.ParseToJson().ParseToObject<T>();
// 这种方式在用 Obfuscator 的时候有问题
//using (MemoryStream stream = new MemoryStream())
//{
// BinaryFormatter formatter = new BinaryFormatter();
// formatter.Serialize(stream, o);
// stream.Position = 0;
// return (T)formatter.Deserialize(stream);
//}
}
#endregion
#region 浅拷贝(拷贝对象里面的数据[property and field],但不拷贝对象里面的子对象)
public static void ShadowClone<T1, T2>(this T1 source, ref T2 destination)
{
var sourceMembers = ReflectionHelper.GetMembers(source.GetType());
var destinationMembers = ReflectionHelper.GetMembers(destination.GetType());
// Copy data from source to destination
foreach (var sourceMember in sourceMembers)
{
if (!ReflectionHelper.CanRead(sourceMember))
{
continue;
}
var destinationMember = destinationMembers.FirstOrDefault(x => x.Name.ToLower() == sourceMember.Name.ToLower());
if (destinationMember == null || !ReflectionHelper.CanWrite(destinationMember))
{
continue;
}
ReflectionHelper.SetObjectValue(ref destination, destinationMember, ReflectionHelper.GetMemberValue(source, sourceMember));
}
}
#endregion
}
}
@@ -0,0 +1,114 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace NaiBa.Util.Extension
{
public static partial class Extensions
{
#region 枚举成员转成dictionary类型
/// <summary>
/// 转成dictionary类型
/// </summary>
/// <param name="enumType"></param>
/// <returns></returns>
public static Dictionary<int, string> EnumToDictionary(this Type enumType)
{
Dictionary<int, string> dictionary = new Dictionary<int, string>();
Type typeDescription = typeof(DescriptionAttribute);
FieldInfo[] fields = enumType.GetFields();
int sValue = 0;
string sText = string.Empty;
foreach (FieldInfo field in fields)
{
if (field.FieldType.IsEnum)
{
sValue = ((int)enumType.InvokeMember(field.Name, BindingFlags.GetField, null, null, null));
object[] arr = field.GetCustomAttributes(typeDescription, true);
if (arr.Length > 0)
{
DescriptionAttribute da = (DescriptionAttribute)arr[0];
sText = da.Description;
}
else
{
sText = field.Name;
}
dictionary.Add(sValue, sText);
}
}
return dictionary.OrderBy(p => p.Key).ToDictionary(p => p.Key, p => p.Value);
}
/// <summary>
/// 枚举成员转成键值对Json字符串
/// </summary>
/// <param name="enumType"></param>
/// <returns></returns>
public static string EnumToDictionaryString(this Type enumType)
{
List<KeyValuePair<int, string>> dictionaryList = EnumToDictionary(enumType).ToList();
var sJson = JsonConvert.SerializeObject(dictionaryList);
return sJson;
}
#endregion
#region 根据类型获取枚举的描述
/// <summary>
/// 获取枚举值对应的描述
/// </summary>
/// <param name="enumType"></param>
/// <returns></returns>
public static string GetDescription(this System.Enum enumType)
{
FieldInfo EnumInfo = enumType.GetType().GetField(enumType.ToString());
if (EnumInfo != null)
{
DescriptionAttribute[] EnumAttributes = (DescriptionAttribute[])EnumInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (EnumAttributes.Length > 0)
{
return EnumAttributes[0].Description;
}
}
return enumType.ToString();
}
#endregion
#region 根据值获取枚举的描述
public static string GetDescriptionByEnum<T>(this object obj)
{
var tEnum = System.Enum.Parse(typeof(T), obj.ParseToString()) as System.Enum;
var description = tEnum.GetDescription();
return description;
}
#endregion
#region 根据描述获取枚举值
public static int GetEnumValueByDescription<T>(this string description)
{
Dictionary<int, string> dict = typeof(T).EnumToDictionary();
int value = dict.Where(p => p.Value == description).Select(p => p.Key).FirstOrDefault();
return value;
}
#endregion
#region 根据枚举名称获取值
public static int GetEnumValueByName<T>(this string name)
{
return (int)System.Enum.Parse(typeof(T), name);
}
#endregion
#region 根据枚举值获取名称
public static object GetEnumNameByValue<T>(this int value)
{
return System.Enum.ToObject(typeof(T), value);
}
#endregion
}
}
@@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NaiBa.Util.Extension
{
public static partial class Extensions
{
public static Exception GetOriginalException(this Exception ex)
{
if (ex.InnerException == null) return ex;
return ex.InnerException.GetOriginalException();
}
}
}
@@ -0,0 +1,110 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
namespace NaiBa.Util.Extension
{
public static class LinqExtensions
{
public static Expression Property(this Expression expression, string propertyName)
{
return Expression.Property(expression, propertyName);
}
public static Expression AndAlso(this Expression left, Expression right)
{
return Expression.AndAlso(left, right);
}
public static Expression Call(this Expression instance, string methodName, params Expression[] arguments)
{
return Expression.Call(instance, instance.Type.GetMethod(methodName), arguments);
}
public static Expression GreaterThan(this Expression left, Expression right)
{
return Expression.GreaterThan(left, right);
}
public static Expression<T> ToLambda<T>(this Expression body, params ParameterExpression[] parameters)
{
return Expression.Lambda<T>(body, parameters);
}
public static Expression<Func<T, bool>> True<T>() { return param => true; }
public static Expression<Func<T, bool>> False<T>() { return param => false; }
/// <summary>
/// 组合And
/// </summary>
/// <returns></returns>
public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second)
{
return first.Compose(second, Expression.AndAlso);
}
/// <summary>
/// 组合Or
/// </summary>
/// <returns></returns>
public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second)
{
return first.Compose(second, Expression.OrElse);
}
/// <summary>
/// Combines the first expression with the second using the specified merge function.
/// </summary>
static Expression<T> Compose<T>(this Expression<T> first, Expression<T> second, Func<Expression, Expression, Expression> merge)
{
var map = first.Parameters
.Select((f, i) => new { f, s = second.Parameters[i] })
.ToDictionary(p => p.s, p => p.f);
var secondBody = ParameterRebinder.ReplaceParameters(map, second.Body);
return Expression.Lambda<T>(merge(first.Body, secondBody), first.Parameters);
}
/// <summary>
/// ParameterRebinder
/// </summary>
private class ParameterRebinder : ExpressionVisitor
{
/// <summary>
/// The ParameterExpression map
/// </summary>
readonly Dictionary<ParameterExpression, ParameterExpression> map;
/// <summary>
/// Initializes a new instance of the <see cref="ParameterRebinder"/> class.
/// </summary>
/// <param name="map">The map.</param>
ParameterRebinder(Dictionary<ParameterExpression, ParameterExpression> map)
{
this.map = map ?? new Dictionary<ParameterExpression, ParameterExpression>();
}
/// <summary>
/// Replaces the parameters.
/// </summary>
/// <param name="map">The map.</param>
/// <param name="exp">The exp.</param>
/// <returns>Expression</returns>
public static Expression ReplaceParameters(Dictionary<ParameterExpression, ParameterExpression> map, Expression exp)
{
return new ParameterRebinder(map).Visit(exp);
}
/// <summary>
/// Visits the parameter.
/// </summary>
/// <param name="p">The p.</param>
/// <returns>Expression</returns>
protected override Expression VisitParameter(ParameterExpression p)
{
ParameterExpression replacement;
if (map.TryGetValue(p, out replacement))
{
p = replacement;
}
return base.VisitParameter(p);
}
}
}
}
@@ -0,0 +1,119 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using NaiBa.Util.Helper;
using Newtonsoft.Json.Linq;
namespace NaiBa.Util.Extension
{
public static partial class Extensions
{
public static bool IsNullOrEmpty(this object value)
{
if (value != null && !string.IsNullOrEmpty(value.ParseToString()))
{
return false;
}
else
{
return true;
}
}
public static bool IsNullOrZero(this object value)
{
if (value == null || string.IsNullOrEmpty(value.ParseToString()) || value.ParseToString().Trim() == "0")
{
return true;
}
else
{
return false;
}
}
public static bool IsNumericType(this object value)
{
if (value == null)
{
return false;
}
switch (Type.GetTypeCode(value.GetType()))
{
case TypeCode.Byte:
case TypeCode.SByte:
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.Decimal:
case TypeCode.Double:
case TypeCode.Single:
return true;
default:
return false;
}
}
public static bool IsStringType(this object value)
{
if (value == null)
{
return false;
}
switch (Type.GetTypeCode(value.GetType()))
{
case TypeCode.String:
return true;
default:
return false;
}
}
public static bool IsNumber(this string value)
{
return RegexHelper.IsNumber(value);
}
public static bool IsAlphabet(this string value)
{
return RegexHelper.IsAlphabet(value);
}
public static bool IsAlphabetOrNumber(this string value)
{
return RegexHelper.IsAlphabetOrNumber(value);
}
public static bool IsJson(this string value)
{
return JsonHelper.IsJson(value);
}
public static bool IsJTokenNullOrEmpty(this JToken token)
{
return (token == null) ||
(token.Type == JTokenType.Array && !token.HasValues) ||
(token.Type == JTokenType.Object && !token.HasValues) ||
(token.Type == JTokenType.String && token.ToString() == string.Empty) ||
(token.Type == JTokenType.Null);
}
public static bool IsAjaxRequest(this Microsoft.AspNetCore.Http.HttpRequest request)
{
if (request == null)
throw new ArgumentNullException("request");
if (request.Headers != null)
return request.Headers["X-Requested-With"] == "XMLHttpRequest";
return false;
}
}
}
@@ -0,0 +1,215 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using NaiBa.Util.Extension;
namespace NaiBa.Util.Helper
{
public class HtmlHelper
{
public static string HtmlEncode(string html)
{
if (string.IsNullOrEmpty(html))
{
return string.Empty;
}
else
{
return WebUtility.HtmlEncode(html);
}
}
public static string HtmlDecode(string url)
{
if (string.IsNullOrEmpty(url))
{
return string.Empty;
}
else
{
return WebUtility.HtmlDecode(url);
}
}
/// <summary>
/// Unicode解码
/// </summary>
/// <param name="html"></param>
/// <returns></returns>
public static string UnicodeDecode(string html)
{
html = WebUtility.HtmlDecode(html);
Regex reUnicode = new Regex(@"\\u([0-9a-fA-F]{4})", RegexOptions.Compiled);
return reUnicode.Replace(html, m =>
{
short c;
if (short.TryParse(m.Groups[1].Value, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out c))
{
return "" + (char)c;
}
return m.Value;
});
}
#region Resove
public static string Resove(string html, string prefix, string subfix = "")
{
int inl = html.IndexOf(prefix);
if (inl == -1)
{
prefix = prefix.Replace("\"", "'");
subfix = subfix.Replace("\"", "'");
inl = html.IndexOf(prefix);
}
if (inl == -1)
{
return null;
}
inl += prefix.Length;
if (!string.IsNullOrEmpty(subfix))
{
int inl2 = html.IndexOf(subfix, inl);
if (inl2 == -1)
{
return null;
}
string result = html.Substring(inl, inl2 - inl);
return result;
}
else
{
string result = html.Substring(inl);
return result;
}
}
#endregion
#region ResoveReverse
public static string ResoveReverse(string html, string subfix, string prefix)
{
int inl = html.IndexOf(subfix);
if (inl == -1)
{
return null;
}
string subString = html.Substring(0, inl);
int inl2 = subString.LastIndexOf(prefix);
if (inl2 == -1)
{
return null;
}
string s = subString.Substring(inl2 + prefix.Length, subString.Length - inl2 - prefix.Length);
return s;
}
#endregion
#region ResoveList
public static List<string> ResoveList(string html, string prefix, string subfix)
{
List<string> list = new List<string>();
int index = 0;
do
{
index = html.IndexOf(prefix, index);
if (index == -1)
{
break;
}
index += prefix.Length;
int indexEnd = html.IndexOf(subfix, index);
if (indexEnd > 0)
{
string content = html.Substring(index, indexEnd - index);
list.Add(content);
}
index = indexEnd;
}
while (index > -1);
return list;
}
#endregion
#region ResoveListByAT
public static List<string> ResoveListByAT(string html)
{
List<string> list = new List<string>();
int index = html.IndexOf('@');
while (index > 0)
{
int indexx = html.LastIndexOf("'", index); //向前一个单引号
int indexy = html.IndexOf("'", index + 1); //向后一个单引号
string s78 = html.Substring(indexx, indexy - indexx);
s78 = s78.Replace("'", "");
list.Add(s78);
index = html.IndexOf('@', indexy);
}
return list;
}
#endregion
/// <summary>
/// 清除HTML代码
/// </summary>
/// <param name="html"></param>
public static string ClearHtml(string html)
{
html = html.ParseToString();
html = Regex.Replace(html, @"(<head[\w\W]*?</head>|<script[\w\W]*?</script>|<style[\w\W]*?</style>|<!--[\w\W]*?-->)", string.Empty);
html = Regex.Replace(html, @"(<span[\w\W]*?</span>)", string.Empty);
html = Regex.Replace(html, "(<[^>]*?>)", string.Empty);
return html;
}
public static string GetHtmlText(string html)
{
html = html.ParseToString();
html = Regex.Replace(html, "<.*?>", string.Empty);
return html;
}
/// <summary>
/// 清除HTML代码A标签
/// </summary>
/// <param name="html"></param>
/// <returns></returns>
public static string ClearHtmlA(string html)
{
html = html.ParseToString();
html = Regex.Replace(html, "(</?a[^>]*>)", "", RegexOptions.IgnoreCase);
return html.Trim();
}
public static string AddEscapeCharacter(string html)
{
html = html.ParseToString();
html = html.Replace("\"", "\\\"");
html = html.Replace("'", "\\'");
return html;
}
public static string TrimBOM(string html)
{
html = html.Trim(new char[] { '\uFEFF' });
return html;
}
public static string TrimJsonp(string json)
{
int start = json.IndexOf("{");
int end = json.LastIndexOf("}");
if (start > 0 && end > 0)
{
return json.Substring(start, end - start + 1);
}
return json;
}
}
}
@@ -0,0 +1,122 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
using NaiBa.Util.Extension;
namespace NaiBa.Util.Helper
{
public class JsonHelper
{
public static bool IsJson(string html)
{
if (string.IsNullOrEmpty(html))
{
return false;
}
html = html.Trim();
if ((html.StartsWith("{") && html.EndsWith("}")) || // For object
(html.StartsWith("[") && html.EndsWith("]"))) // For array
{
try
{
var obj = JToken.Parse(html);
return true;
}
catch
{
return false;
}
}
return false;
}
public static string JsonAlphabeticaly(string json)
{
json = json.ParseToString().Trim();
if (json.StartsWith("{"))
{
var jObj = JObject.Parse(json);
JObject result = new JObject();
OrderJson(result, jObj);
return result.ToString();
}
else
{
var jArr = JArray.Parse(json);
JArray result = new JArray();
foreach (var arr in jArr)
{
result.Add(new JObject());
OrderJson((JObject)result[result.Count - 1], (JObject)arr);
}
return result.ToString();
}
}
public static string SerializeAlphabeticaly(object obj)
{
return JsonConvert.SerializeObject(obj, Formatting.Indented, new JsonSerializerSettings { ContractResolver = new OrderedContractResolver() });
}
public static string TrimJsonp(string json)
{
return HtmlHelper.TrimJsonp(json);
}
#region 私有方法
private static void OrderJson(JObject jObj, JObject item)
{
foreach (var property in item.Children<JProperty>().OrderBy(p => p.Name))
{
switch (property.Value.Type.ToString())
{
case "Array":
var jArr = new JArray();
jObj.Add(property.Name, jArr);
for (int i = 0; i < property.Value.Count(); i++)
{
switch (property.Value[i].Type.ToString())
{
case "Object":
var obj = new JObject();
jArr.Add(obj);
OrderJson(obj, (JObject)property.Value[i]);
break;
default:
jArr.Add(property.Value[i]);
break;
}
}
break;
case "Object":
jObj.Add(property.Name, new JObject());
OrderJson((JObject)jObj[property.Name], (JObject)property.Value);
break;
default:
jObj.Add(property.Name, property.Value);
break;
}
}
}
#endregion
}
public class OrderedContractResolver : DefaultContractResolver
{
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
return base.CreateProperties(type, memberSerialization)
.OrderBy(p => p.Order ?? int.MaxValue) // Honour any explit ordering first
.ThenBy(p => p.PropertyName)
.ToList();
}
}
}
@@ -0,0 +1,220 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.Concurrent;
using System.Reflection;
using System.Linq.Expressions;
using NaiBa.Util.Extension;
namespace NaiBa.Util.Helper
{
public class ReflectionHelper
{
private static ConcurrentDictionary<string, object> dictCache = new ConcurrentDictionary<string, object>();
#region 得到类里面的属性集合
public static PropertyInfo[] GetProperties(Type type, string[] columns = null)
{
PropertyInfo[] properties = null;
if (dictCache.ContainsKey(type.FullName))
{
properties = dictCache[type.FullName] as PropertyInfo[];
}
else
{
properties = type.GetProperties();
dictCache.TryAdd(type.FullName, properties);
}
if (columns != null && columns.Length > 0)
{
// 按columns顺序返回属性
var columnPropertyList = new List<PropertyInfo>();
foreach (var column in columns)
{
var columnProperty = properties.Where(p => p.Name == column).FirstOrDefault();
if (columnProperty != null)
{
columnPropertyList.Add(columnProperty);
}
}
return columnPropertyList.ToArray();
}
else
{
return properties;
}
}
#endregion
public static List<MemberInfo> GetMembers(Type type)
{
var flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
var members = new List<MemberInfo>();
members.AddRange(type.GetProperties(flags));
members.AddRange(type.GetFields(flags));
return members;
}
public static void SetObjectPropertyValue<T>(string propertyName, object value)
{
var type = typeof(T);
var field = type.GetProperty(propertyName);
if (field != null)
{
field.SetValue(null, value);
}
}
public static void SetObjectPropertyValue(object obj, string propertyName, object value)
{
if (obj != null)
{
PropertyInfo propertyInfo = GetProperties(obj.GetType()).Where(p => p.Name == propertyName).FirstOrDefault();
// make sure object has the property we are after
if (propertyInfo != null)
{
switch (propertyInfo.PropertyType.FullName)
{
case "System.Int32": propertyInfo.SetValue(obj, value.ParseToInt(), null); break;
case "System.Int64": propertyInfo.SetValue(obj, value.ParseToLong(), null); break;
case "System.Decimal": propertyInfo.SetValue(obj, value.ParseToDecimal(), null); break;
case "System.Double": propertyInfo.SetValue(obj, value.ParseToDouble(), null); break;
default:
if (propertyInfo.PropertyType.GenericTypeArguments.Length > 0)
{
switch (propertyInfo.PropertyType.GenericTypeArguments[0].FullName)
{
case "System.DateTime":
if (!string.IsNullOrEmpty(value.ParseToString()))
{
propertyInfo.SetValue(obj, value.ParseToString().ParseToDateTime(), null);
}
break;
case "System.Decimal":
propertyInfo.SetValue(obj, value.ParseToDecimal(), null);
break;
}
}
else
{
propertyInfo.SetValue(obj, value, null);
}
break;
}
}
}
}
public static object GetObjectPropertyValue(object obj, string propertyName)
{
if (obj != null)
{
PropertyInfo propertyInfo = GetProperties(obj.GetType()).Where(p => p.Name == propertyName).FirstOrDefault();
// make sure object has the property we are after
if (propertyInfo != null)
{
return propertyInfo.GetValue(obj);
}
}
return null;
}
public static string GetGenericName(Type type)
{
if (type.GetGenericArguments().Length > 0)
{
return GetGenericName(type.GetGenericArguments().FirstOrDefault());
}
else
{
if (type.GetGenericArguments().FirstOrDefault() != null)
{
return type.GetGenericArguments().FirstOrDefault().Name;
}
else
{
return type.Name;
}
}
}
public static string GetMemberName<T>(Expression<Func<T>> memberExpression)
{
MemberExpression expressionBody = (MemberExpression)memberExpression.Body;
return expressionBody.Member.Name;
}
public static void SetObjectValue<T>(ref T obj, MemberInfo member, object value)
{
// Boxing method used for modifying structures
var boxed = obj.GetType().IsValueType ? (object)obj : obj;
SetMemberValue(ref boxed, member, value);
obj = (T)boxed;
}
public static void SetMemberValue<T>(ref T obj, MemberInfo member, object value)
{
if (IsProperty(member))
{
var prop = (PropertyInfo)member;
if (prop.SetMethod != null)
{
prop.SetValue(obj, value);
}
}
else if (IsField(member))
{
var field = (FieldInfo)member;
field.SetValue(obj, value);
}
}
public static object GetMemberValue(object obj, MemberInfo member)
{
object result = null;
if (IsProperty(member))
{
var prop = (PropertyInfo)member;
result = prop.GetValue(obj, prop.GetIndexParameters().Count() == 1 ? new object[] { null } : null);
}
else if (IsField(member))
{
var field = (FieldInfo)member;
result = field.GetValue(obj);
}
return result;
}
public static bool CanWrite(MemberInfo member)
{
return IsProperty(member) ? ((PropertyInfo)member).CanWrite : IsField(member);
}
public static bool CanRead(MemberInfo member)
{
return IsProperty(member) ? ((PropertyInfo)member).CanRead : IsField(member);
}
#region 私有方法
private static bool IsProperty(MemberInfo member)
{
return IsType(member.GetType(), typeof(PropertyInfo));
}
private static bool IsField(MemberInfo member)
{
return IsType(member.GetType(), typeof(FieldInfo));
}
private static bool IsType(System.Type type, System.Type targetType)
{
return type.Equals(targetType) || type.IsSubclassOf(targetType);
}
#endregion
}
}
@@ -0,0 +1,81 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace NaiBa.Util.Helper
{
public class RegexHelper
{
// <span\\sclass=\"rantings-num\".*?>(.+?)</span>
/// <summary>
/// 返回正则对象所有结果
/// </summary>
/// <param name="html"></param>
/// <param name="regex"></param>
/// <returns></returns>
public static MatchCollection GetMatchCollection(string html, string regex)
{
if (string.IsNullOrEmpty(html))
{
return null;
}
return Regex.Matches(html, regex, RegexOptions.IgnoreCase);
}
/// <summary>
/// 返回单个正则分析结果
/// </summary>
/// <param name="html"></param>
/// <param name="regex"></param>
/// <returns></returns>
public static string GetMatch(string html, string regex, int index = 0)
{
if (string.IsNullOrEmpty(html))
{
return string.Empty;
}
MatchCollection mc = Regex.Matches(html, regex, RegexOptions.IgnoreCase);
if (mc.Count > 0)
{
return mc[index].Groups[1].Value.ToString();
}
return string.Empty;
}
public static string GetMatchWithSingleLine(string html, string regex)
{
if (string.IsNullOrEmpty(html))
{
return string.Empty;
}
MatchCollection mc = Regex.Matches(html, regex, RegexOptions.IgnoreCase | RegexOptions.Singleline);
if (mc.Count > 0)
{
return mc[0].Groups[1].ToString();
}
return string.Empty;
}
public static bool IsNumber(string str)
{
Regex regex = new Regex(@"^[0-9\.]+$");
return regex.IsMatch(str);
}
public static bool IsAlphabet(string str)
{
Regex regex = new Regex(@"^[A-Za-z]+$");
return regex.IsMatch(str);
}
public static bool IsAlphabetOrNumber(string str)
{
Regex regex = new Regex(@"^[A-Za-z0-9]+$");
return regex.IsMatch(str);
}
}
}
+417
View File
@@ -0,0 +1,417 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Net.Cache;
using System.Net.Security;
using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
namespace StoreHub.KJDWebService.Commons
{
public class HtmlUtils
{
static public string UrlDecodeUtf8(string value)
{
if (value == null)
{
return null;
}
Encoding encoding = Encoding.UTF8;//你的编码 也可能是GBK
int length = value.Length;
UrlDecoder decoder = new UrlDecoder(length, encoding);
for (int i = 0; i < length; i++)
{
char ch = value[i];
if (ch == '+')
{
ch = ' ';
}
else if ((ch == '%') && (i < (length - 2)))
{
if ((value[i + 1] == 'u') && (i < (length - 5)))
{
int num3 = HexToInt(value[i + 2]);
int num4 = HexToInt(value[i + 3]);
int num5 = HexToInt(value[i + 4]);
int num6 = HexToInt(value[i + 5]);
if (((num3 < 0) || (num4 < 0)) || ((num5 < 0) || (num6 < 0)))
{
goto Label_010B;
}
ch = (char)((((num3 << 12) | (num4 << 8)) | (num5 << 4)) | num6);
i += 5;
decoder.AddChar(ch);
continue;
}
int num7 = HexToInt(value[i + 1]);
int num8 = HexToInt(value[i + 2]);
if ((num7 >= 0) && (num8 >= 0))
{
byte b = (byte)((num7 << 4) | num8);
i += 2;
decoder.AddByte(b);
continue;
}
}
Label_010B:
if ((ch & 0xff80) == 0)
{
decoder.AddByte((byte)ch);
}
else
{
decoder.AddChar(ch);
}
}
return decoder.GetString();
}
/// <summary>
/// URL UTF-8转码
/// </summary>
/// <param name="IndexKey"></param>
/// <returns></returns>
public static string UrlEncodeUtf8(string IndexKey)
{
if (String.IsNullOrEmpty(IndexKey))
return "";
return WebUtility.UrlEncode(IndexKey);
}
/// <summary>
/// post 数据
/// </summary>
/// <param name="url"></param>
/// <param name="postData"></param>
/// <returns></returns>
public static string PostUtf8(string url, StringBuilder postData)
{
try
{
WebClientx wc = new WebClientx();
byte[] sendData = Encoding.GetEncoding("utf-8").GetBytes(postData.ToString());
wc.Headers.Add("ContentLength", sendData.Length.ToString());
wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
wc.Proxy = null;
return Encoding.UTF8.GetString(wc.UploadData(url, "POST", sendData));
}
catch
{
return "";
}
}
/// <summary>
/// 浏览器标识
/// </summary>
public static string UserAgent = @"Mozilla/5.0+(Windows+NT+10.0;+WOW64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/57.0.2987.133+Safari/537.36
Mozilla/5.0+(Windows+NT+6.1)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/57.0.2987.133+Safari/537.36
Mozilla/5.0+(Windows+NT+10.0;+WOW64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/54.0.2840.99+Safari/537.36
Mozilla/5.0+(Windows+NT+5.1)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/31.0.1650.63+Safari/537.36
Mozilla/5.0+(compatible;+MSIE+9.0;+Windows+NT+6.1;+Win64;+x64;+Trident/5.0)
Mozilla/5.0+(Windows+NT+5.1)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/45.0.2454.101+Safari/537.36
Mozilla/5.0+(Windows+NT+6.1;+WOW64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/45.0.2454.101+Safari/537.36
Mozilla/5.0+(Windows+NT+6.3;+WOW64;+Trident/7.0;+rv:11.0)+like+Gecko
Mozilla/5.0+(Windows+NT+10.0;+WOW64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/57.0.2987.133+Safari/537.36
Mozilla/5.0+(compatible;+MSIE+9.0;+Windows+NT+6.1;+WOW64;+Trident/5.0)
Mozilla/5.0+(Windows+NT+6.3;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/57.0.2987.133+Safari/537.36
Mozilla/5.0+(Windows+NT+6.1;+WOW64)+AppleWebKit/537.1+(KHTML,+like+Gecko)+Chrome/21.0.1180.89+Safari/537.1
Mozilla/5.0+(Windows+NT+6.1;+WOW64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/45.0.2454.101+Safari/537.36
Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.104 Safari/537.36 Core/1.53.2372.400 QQBrowser/9.5.10548.400";
/// <summary>
/// post 数据
/// </summary>
/// <param name="url"></param>
/// <param name="postData"></param>
/// <returns></returns>
public static string PostUtf8(string url, string postData, string contentType = "")
{
//return PostUtf8(url, Encoding.UTF8.GetBytes(postData));
bool isError = false;
string[] l = UserAgent.Split('\n');
reTry:
try
{
string codeType = "utf-8";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.UserAgent = l[new Random(Guid.NewGuid().GetHashCode()).Next(l.Length)].Trim();
byte[] byteData = Encoding.GetEncoding(codeType).GetBytes(postData);
request.Method = "POST";
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
request.Timeout = 30 * 1000;
request.ReadWriteTimeout = 30 * 1000;
request.Proxy = null;
request.ContentType = "application/x-www-form-urlencoded; charset=" + codeType;
//if (BaseClass.SaLevel > 0)
{
//260306 采用GZip/deflate压缩
//request.Headers.Set(HttpRequestHeader.AcceptEncoding, "gzip, deflate, br, zstd");
//request.Headers.Set(HttpRequestHeader.AcceptEncoding, "gzip, deflate");
}
if (url.StartsWith("https://openapi.jinritemai.com/"))
{
request.Headers.Add("X-USE-BOE", "1");
request.Headers.Add("Origin-From", "djt_prod");
request.Headers.Add("djt_prod", "boe_time_sku");
}
if (!string.IsNullOrEmpty(contentType))
{
request.ContentType = contentType;
}
request.ContentLength = byteData.Length;
request.Referer = url;
request.CookieContainer = new CookieContainer();
request.AllowAutoRedirect = false;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(byteData, 0, byteData.Length);
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream receiveStream = response.GetResponseStream();
StreamReader readStream = new StreamReader(receiveStream, Encoding.GetEncoding(codeType));
return readStream.ReadToEnd().Trim();
}
catch (Exception e)
{
//{
// isError = true;
// goto reTry;
//}
Thread.Sleep(50);
return "";
}
}
public static int HexToInt(char h)
{
if ((h >= '0') && (h <= '9'))
{
return (h - '0');
}
if ((h >= 'a') && (h <= 'f'))
{
return ((h - 'a') + 10);
}
if ((h >= 'A') && (h <= 'F'))
{
return ((h - 'A') + 10);
}
return -1;
}
}
/// <summary>
/// class UrlDecoder
/// </summary>
class UrlDecoder
{
// Fields
private int _bufferSize;
private byte[] _byteBuffer;
private char[] _charBuffer;
private Encoding _encoding;
private int _numBytes;
private int _numChars;
// Methods
internal UrlDecoder(int bufferSize, Encoding encoding)
{
this._bufferSize = bufferSize;
this._encoding = encoding;
this._charBuffer = new char[bufferSize];
}
internal void AddByte(byte b)
{
if (this._byteBuffer == null)
{
this._byteBuffer = new byte[this._bufferSize];
}
this._byteBuffer[this._numBytes++] = b;
}
internal void AddChar(char ch)
{
if (this._numBytes > 0)
{
this.FlushBytes();
}
this._charBuffer[this._numChars++] = ch;
}
private void FlushBytes()
{
if (this._numBytes > 0)
{
this._numChars += this._encoding.GetChars(this._byteBuffer, 0, this._numBytes, this._charBuffer, this._numChars);
this._numBytes = 0;
}
}
internal string GetString()
{
if (this._numBytes > 0)
{
this.FlushBytes();
}
if (this._numChars > 0)
{
return new string(this._charBuffer, 0, this._numChars);
}
return string.Empty;
}
}
/// <summary>
/// 下载器
/// </summary>
public class WebClientx : WebClient
{
/// <summary>
/// 默认超时多少秒
/// </summary>
public int Timeout = 100;
/// <summary>
/// 允许自动重定向
/// </summary>
public bool AllowAutoRedirect = true;
public bool IsDelete = false;
private string OutIP = "";
/// <summary>
/// 证书列表
/// </summary>
public static List<Certificate> X509List = new List<Certificate>();
/// <summary>
/// 绑定IP
/// </summary>
/// <param name="outIp"></param>
public WebClientx(string outIp)
{
OutIP = outIp;
CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore);
}
public WebClientx()
{
}
/// <summary>
/// 重写
/// </summary>
/// <param name="address"></param>
/// <returns></returns>
protected override WebRequest GetWebRequest(Uri address)
{
string s = address.ToString();
if (string.IsNullOrEmpty(s) || s.Length < 7 || !(s.Substring(0, 7).ToLower() == "http://" || s.Substring(0, 8).ToLower() == "https://"))
return null;
var request = (HttpWebRequest)base.GetWebRequest(address);
request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
request.Timeout = 1000 * Timeout;
request.ReadWriteTimeout = 500 * Timeout;
request.AllowAutoRedirect = AllowAutoRedirect;
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate);
if (IsDelete)
request.Method = "DELETE";
if (!string.IsNullOrEmpty(OutIP))
{
request.ServicePoint.BindIPEndPointDelegate = (servicePoint, remoteEndPoint, retryCount) =>
{
servicePoint.MaxIdleTime = 20;
return new IPEndPoint(IPAddress.Parse(OutIP), 0);
};
}
if (request.RequestUri.Scheme == "https") //挂接验证服务端证书的回调
{
X509Certificate2 x509c = null;
for (int i = 0; i < X509List.Count; i++)
{
if (X509List[i].Domain.ToLower() == address.Host.ToLower())
{
x509c = X509List[i].X509;
break;
}
}
if (x509c == null)
{
ServicePointManager.ServerCertificateValidationCallback =
new RemoteCertificateValidationCallback(RemoteCertificateValidationCallback);
try
{
X509Store _store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
_store.Open(OpenFlags.ReadWrite);
string findValue = Dns.GetHostName(); //获取本地主机名称作为证书查找的参数
X509Certificate2Collection _certsCollection =
_store.Certificates.Find(X509FindType.FindByIssuerName, findValue, false);
if (_certsCollection.Count > 0)
{
x509c = _certsCollection[0];
request.ClientCertificates.Add(x509c);
}
}
catch { }
}
}
return request;
}
/// <summary>
/// 获取证书
/// </summary>
/// <param name="sender"></param>
/// <param name="certificate"></param>
/// <param name="chain"></param>
/// <param name="sslPolicyErrors"></param>
/// <returns></returns>
public bool RemoteCertificateValidationCallback(Object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
return true;
}
public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
//if (sslPolicyErrors == SslPolicyErrors.None) {
// return true;
//}
//Console.WriteLine("Certificate error: {0}", sslPolicyErrors);
//// Do not allow this client to communicate with unauthenticated servers.
//return false;
return true;
}
}
/// <summary>
/// 网站证书
/// </summary>
public class Certificate
{
/// <summary>
/// 域名
/// </summary>
public string Domain { get; set; }
/// <summary>
/// 证书
/// </summary>
public X509Certificate2 X509 { get; set; }
}
}
+380
View File
@@ -0,0 +1,380 @@
using NaiBa.Util.Extension;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace StoreHub.KJDWebService.Commons
{
public class HttpUtils
{
public static string WxApiPostResponse(string _url, string _data, string referer)
{
HttpWebResponse response = null;
string result;
try
{
string url = _url;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.KeepAlive = true;
request.Headers.Set(HttpRequestHeader.CacheControl, "max-age=0");
request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36";
request.ContentType = "application/json";
request.Accept = "*/*";
request.Referer = referer;
request.Headers.Set(HttpRequestHeader.AcceptEncoding, "gzip, deflate, br, zstd");
request.Headers.Set(HttpRequestHeader.AcceptLanguage, "zh-CN,zh;q=0.9");
request.Method = "POST";
request.ServicePoint.Expect100Continue = false;
string body = _data;
byte[] postBytes = System.Text.Encoding.UTF8.GetBytes(body);
request.ContentLength = postBytes.Length;
Stream stream = request.GetRequestStream();
stream.Write(postBytes, 0, postBytes.Length);
stream.Close();
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
if (ex.Status == WebExceptionStatus.ProtocolError)
{
response = (HttpWebResponse)ex.Response;
result = ReadResponse(response);
return result;
}
else return ex.Message;
}
catch (Exception e)
{
if (response != null) response.Close();
return e.Message;
}
result = ReadResponse(response);
return result;
}
public static string WxApiGetResponse(string _url, string referer)
{
HttpWebResponse response = null;
string result;
try
{
string url = _url;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.KeepAlive = true;
request.Headers.Set(HttpRequestHeader.CacheControl, "max-age=0");
request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36";
request.ContentType = "application/json";
request.Accept = "*/*";
request.Referer = referer;
request.Headers.Set(HttpRequestHeader.AcceptEncoding, "gzip, deflate, br, zstd");
request.Headers.Set(HttpRequestHeader.AcceptLanguage, "zh-CN,zh;q=0.9");
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
if (ex.Status == WebExceptionStatus.ProtocolError)
{
response = (HttpWebResponse)ex.Response;
result = ReadResponse(response);
return result;
}
else return ex.Message;
}
catch (Exception e)
{
if (response != null) response.Close();
return e.Message;
}
result = ReadResponse(response);
return result;
}
public static string e57PostResponse(string _url, string _data, string referer)
{
HttpWebResponse response = null;
string result;
try
{
string url = _url;
HttpWebRequest request;
if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
ServicePointManager.SecurityProtocol =
ServicePointManager.SecurityProtocol | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
request = WebRequest.Create(url) as HttpWebRequest;
request.ProtocolVersion = HttpVersion.Version10;
}
else
request = (HttpWebRequest)WebRequest.Create(url);
request.KeepAlive = true;
request.Headers.Set(HttpRequestHeader.CacheControl, "max-age=0");
request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36";
request.ContentType = "application/json";
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7"; //request.Accept = "*/*";
request.Referer = referer;
request.Headers.Set(HttpRequestHeader.AcceptEncoding, "gzip, deflate");
request.Headers.Set(HttpRequestHeader.AcceptLanguage, "zh-CN,zh;q=0.9");
request.Method = "POST";
request.ServicePoint.Expect100Continue = false;
string body = _data;
byte[] postBytes = System.Text.Encoding.UTF8.GetBytes(body);
request.ContentLength = postBytes.Length;
Stream stream = request.GetRequestStream();
stream.Write(postBytes, 0, postBytes.Length);
stream.Close();
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
if (ex.Status == WebExceptionStatus.ProtocolError)
{
response = (HttpWebResponse)ex.Response;
result = ReadResponse(response);
return result;
}
else return ex.Message;
}
catch (Exception e)
{
if (response != null) response.Close();
return e.Message;
}
result = ReadResponse(response);
return result;
}
public static string e57GetResponse(string _url, string referer)
{
HttpWebResponse response = null;
string result;
try
{
string url = _url;
HttpWebRequest request;
if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;
ServicePointManager.SecurityProtocol =
ServicePointManager.SecurityProtocol | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
request = WebRequest.Create(url) as HttpWebRequest;
request.ProtocolVersion = HttpVersion.Version10;
}
else
request = (HttpWebRequest)WebRequest.Create(url);
request.KeepAlive = true;
request.Headers.Add("sec-ch-ua", @"""Not(A:Brand"";v=""8"", ""Chromium"";v=""144"", ""Google Chrome"";v=""144""");
request.Headers.Add("sec-ch-ua-mobile", @"?0");
request.Headers.Add("sec-ch-ua-platform", @"""Windows""");
request.Headers.Add("Upgrade-Insecure-Requests", @"1");
request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/144.0.0.0 Safari/537.36";
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7";
request.Headers.Add("Sec-Fetch-Site", @"none");
request.Headers.Add("Sec-Fetch-Mode", @"navigate");
request.Headers.Add("Sec-Fetch-User", @"?1");
request.Headers.Add("Sec-Fetch-Dest", @"document");
request.Headers.Set(HttpRequestHeader.AcceptEncoding, "gzip, deflate");
request.Headers.Set(HttpRequestHeader.AcceptLanguage, "zh-CN,zh;q=0.9");
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
if (ex.Status == WebExceptionStatus.ProtocolError)
{
response = (HttpWebResponse)ex.Response;
result = ReadResponse(response);
return result;
}
else return ex.Message;
}
catch (Exception e)
{
if (response != null) response.Close();
return e.Message;
}
result = ReadResponse(response);
return result;
}
public static string ReadResponse(HttpWebResponse response)
{
using (Stream responseStream = response.GetResponseStream())
{
Stream streamToRead = responseStream;
if (response.ContentEncoding.ToLower().Contains("gzip"))
{
streamToRead = new GZipStream(streamToRead, CompressionMode.Decompress);
}
else if (response.ContentEncoding.ToLower().Contains("deflate"))
{
streamToRead = new DeflateStream(streamToRead, CompressionMode.Decompress);
}
using (StreamReader streamReader = new StreamReader(streamToRead, Encoding.UTF8))
{
return streamReader.ReadToEnd();
}
}
}
public static void WriteMultipartBodyToRequest(HttpWebRequest request, string body)
{
string[] multiparts = Regex.Split(body, @"<!>");
byte[] bytes;
using (MemoryStream ms = new MemoryStream())
{
foreach (string part in multiparts)
{
if (File.Exists(part))
{
bytes = File.ReadAllBytes(part);
}
else
{
bytes = System.Text.Encoding.UTF8.GetBytes(part.Replace("\r\n", "\n").Replace("\r", "\n").Replace("\n", "\r\n"));
}
ms.Write(bytes, 0, bytes.Length);
}
request.ContentLength = ms.Length;
using (Stream stream = request.GetRequestStream())
{
ms.WriteTo(stream);
}
}
}
/// <summary>
/// 读取网络图片转为Img以在DataGridView中显示,用于HttpWebRequest直接读取可能403的情况
/// </summary>
/// <param name="imgUrl"></param>
/// <param name="rst"></param>
/// <returns></returns>
public static Image GetUrlImg(string imgUrl, out string rst)
{
rst = "";
//return LoadImage(imgUrl);
Image image = null;
HttpWebResponse response = null;
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(imgUrl);
request.KeepAlive = true;
request.Headers.Set(HttpRequestHeader.CacheControl, "max-age=0");
request.Headers.Add("Upgrade-Insecure-Requests", @"1");
request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36";
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7";
request.Headers.Set(HttpRequestHeader.AcceptEncoding, "gzip, deflate");
request.Headers.Set(HttpRequestHeader.AcceptLanguage, "zh-CN,zh;q=0.9");
//request.IfModifiedSince = DateTime.Parse("Fri, 18 Jul 2025 06:00:49 GMT"); // 没改动不更新,CS程序无缓存不使用
response = (HttpWebResponse)request.GetResponse();
using (Stream stream = response.GetResponseStream())
{
image = Image.FromStream(stream);
}
}
catch (WebException ex)
{
if (ex.Status == WebExceptionStatus.ProtocolError)
{
response = (HttpWebResponse)ex.Response;
rst = ReadResponse(response);
}
if (string.IsNullOrEmpty(rst))
rst = ex.Message;
}
catch (Exception e)
{
rst = e.Message;
}
if (response != null)
{
response.Close();
response.Dispose();
}
return image;
}
public static string WxApiUploadImgFile(string filePath, int width, int height, string accessToken)
{
string boundary = "----WebKitFormBoundaryeZuqpVO6jYOF5Y6S";
HttpWebResponse response = null;
string result;
try
{
string url = "https://api.weixin.qq.com/shop/ec/basics/img/upload?access_token=" + accessToken +
"&upload_type=0&resp_type=1&height=" + height + "&width=" + width;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.KeepAlive = true;
request.Headers.Set(HttpRequestHeader.CacheControl, "max-age=0");
request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36";
request.ContentType = "multipart/form-data; boundary=" + boundary;
request.Accept = "*/*";
request.Referer = "";
request.Headers.Set(HttpRequestHeader.AcceptEncoding, "gzip, deflate");
request.Headers.Set(HttpRequestHeader.AcceptLanguage, "zh-CN,zh;q=0.9");
request.Method = "POST";
request.ServicePoint.Expect100Continue = false;
string body = @"--" + boundary + @"
Content-Disposition: form-data; name=""media""; filename=""" + Path.GetFileName(filePath) + @"""
Content-Type: image/jpg
<!>" + filePath + @"<!>
--" + boundary + @"--
";
WriteMultipartBodyToRequest(request, body);
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
if (ex.Status == WebExceptionStatus.ProtocolError)
{
response = (HttpWebResponse)ex.Response;
result = ReadResponse(response);
return result;
}
else return ex.Message;
}
catch (Exception e)
{
if (response != null) response.Close();
return e.Message;
}
result = ReadResponse(response);
return result;
}
}
}
+138
View File
@@ -0,0 +1,138 @@
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace StoreHub.KJDWebService.Commons
{
public class JsonUtils
{
/// <summary>
/// 反序列化Json字符串生成对象实体
/// </summary>
/// <typeparam name="T">对象类型</typeparam>
/// <param name="jsonStr">json字符串</param>
/// <returns>对象实体</returns>
public static T DeserializeJsonToObject<T>(string jsonStr) where T : class
{
try
{
JsonSerializer serializer = new JsonSerializer();
StringReader sr = new StringReader(jsonStr);
object obj = serializer.Deserialize(new JsonTextReader(sr), typeof(T));
T t = obj as T;
return t;
}
catch
{
return null;
}
}
public static string SerializeObject(object obj)
{
return SerializeObjectToString(obj);
}
public static string SerializeObjectToString(object obj, JsonSerializerSettings jsonsetting = null)
{
try
{
string str = "";
if (jsonsetting != null)
str = JsonConvert.SerializeObject(obj, Formatting.None, jsonsetting);
else
str = JsonConvert.SerializeObject(obj, Formatting.None);
return str;
}
catch
{
return null;
}
}
public static T DeserializeJsonToObjectNullable<T>(string json) where T : class
{
try
{
JsonSerializer serializer = new JsonSerializer();
StringReader sr = new StringReader(json);
object o = serializer.Deserialize(new JsonTextReader(sr), typeof(T));
T t = o as T;
return t;
}
catch
{
return null;
}
}
public static JObject JObjectParse(string json, JsonLoadSettings settings = null)
{
try
{
if (settings == null)
{
JObject obj = JObject.Parse(json);
return obj;
}
else
{
JObject obj = JObject.Parse(json, settings);
return obj;
}
}
catch
{
return null;
}
}
/// <summary>
/// 解析JSON数组生成对象实体集合
/// </summary>
/// <typeparam name="T">对象类型</typeparam>
/// <param name="json">json数组字符串(eg.[{"ID":"112","Name":"石子儿"}])</param>
/// <returns>对象实体集合</returns>
public static List<T> DeserializeJsonToList<T>(string json) where T : class
{
JsonSerializer serializer = new JsonSerializer();
StringReader sr = new StringReader(json);
object o = serializer.Deserialize(new JsonTextReader(sr), typeof(List<T>));
List<T> list = o as List<T>;
return list;
}
public static List<T> DeserializeJsonToListNullable<T>(string json) where T : class
{
try
{
JsonSerializer serializer = new JsonSerializer();
StringReader sr = new StringReader(json);
object o = serializer.Deserialize(new JsonTextReader(sr), typeof(List<T>));
List<T> list = o as List<T>;
return list;
}
catch
{
return null;
}
}
/// <summary>
/// 反序列化JSON到给定的匿名对象.
/// </summary>
/// <typeparam name="T">匿名对象类型</typeparam>
/// <param name="json">json字符串</param>
/// <param name="anonymousTypeObject">匿名对象</param>
/// <returns>匿名对象</returns>
public static T DeserializeAnonymousType<T>(string json, T anonymousTypeObject)
{
T t = JsonConvert.DeserializeAnonymousType(json, anonymousTypeObject);
return t;
}
}
}
+41
View File
@@ -0,0 +1,41 @@
using Microsoft.Extensions.Configuration;
namespace StoreHub.KJDWebService.Commons
{
/// <summary>
/// 业务配置读取(旧 System.Configuration.ConfigurationManager 迁移)。
/// 连接串读 ConnectionStrings 节;业务开关读 KJDConfig 节。
/// 由宿主 Program.cs 在启动时初始化。
/// </summary>
public static class KJDConfig
{
private static IConfiguration _configuration;
public static void SetConfiguration(IConfiguration configuration)
{
_configuration = configuration;
}
public static string GetConnection(string key)
{
if (_configuration == null)
return null;
var v = _configuration[$"ConnectionStrings:{key}"];
if (!string.IsNullOrEmpty(v))
return v;
v = _configuration.GetConnectionString(key);
return v;
}
/// <summary>读取配置值(对应旧 connectionStrings["key"].ConnectionString)</summary>
public static string Get(string key)
{
if (_configuration == null)
return null;
// 优先业务配置节,其次连接串
var v = _configuration[$"KJDConfig:{key}"];
if (!string.IsNullOrEmpty(v))
return v;
v = _configuration.GetConnectionString(key);
return v;
}
}
}
+835
View File
@@ -0,0 +1,835 @@
using FreeSql;
using Microsoft.Extensions.DependencyInjection;
using MySql.Data.MySqlClient;
using System.Data;
using System.Security.Cryptography;
namespace StoreHub.KJDWebService.Commons
{
public class MysqlUtils
{
public string Message = "";
/// <summary>
/// 数据库连接字符串
/// </summary>
private string ConnString = "";
/// <summary>
/// 数据库连接
/// </summary>
private MySqlConnection Conn;
/// <summary>
/// 数据库读取对象
/// </summary>
private MySqlDataReader reader;
/// <summary>
/// 数据库执行对象
/// </summary>
private MySqlCommand cmd = new MySqlCommand();
/// <summary>
/// 错误信息
/// </summary>
//public static string ErrorString = "";
/// <summary>
/// 超时(秒)
/// </summary>
public int TimeOut = 120;
/// <summary>
/// 链接状态
/// </summary>
public bool Connected
{
get { return Conn != null && Conn.State == ConnectionState.Open; }
}
/// <summary>
/// 是否正在执行
/// </summary>
public bool IsRunning = false;
public bool IsUseTrans { get; set; } = false;
public MySqlTransaction Transaction { get; set; } = null;
/// <summary>
/// 初始化数据库链接
/// </summary>
/// <param name="connString">数据库链接</param>
public MysqlUtils(string connString, bool isUseTrans = false)
{
this.IsUseTrans = isUseTrans;
ConnString = KJDConfig.GetConnection(connString);
ConnTo();
}
/// <summary>
/// 去掉SQL中的特殊字符
/// </summary>
/// <param name="value">字符串</param>
/// <returns></returns>
public string ReplaceSql(string value)
{
return ReplaceSqlSpecial(value);
}
/// <summary>
/// 反转字符串,用于mysql反向索引
/// </summary>
/// <param name="temp"></param>
/// <returns></returns>
public static string ReverseString(string temp)
{
if (string.IsNullOrEmpty(temp))
return null;
char[] l = temp.ToCharArray();
Array.Reverse(l);
return new string(l);
}
/// <summary>
/// 去掉SQL中的特殊字符
/// </summary>
/// <param name="value">字符串</param>
/// <returns></returns>
public static string ReplaceSqlSpecial(string value)
{
if (string.IsNullOrEmpty(value))
return null;
value = value.Replace("\\", "\\\\");
value = value.Replace("'", "''");
//value = value.Replace("\"", "\\\"");
return value;
}
///// <summary>
///// 开放一个Conn获取路径,以便外部使用事务提交
///// </summary>
//public MySqlConnection GetConn()
//{
// //Transaction = Conn.BeginTransaction();
// return Conn;
//}
/// <summary>
/// 插入数据
/// </summary>
/// <param name="table"></param>
/// <param name="keys"></param>
/// <returns></returns>
public int Insert(string table, List<MysqlKeyValue> keys)
{
string temp = "", tempx = "";
for (int i = 0; i < keys.Count; i++)
{
temp += ",`" + keys[i].Key + "`";
tempx += ",'" + keys[i].Value + "'";
}
temp = temp.Substring(1);
tempx = tempx.Substring(1);
string sql = "insert into " + table + " (" + temp + ") values (" + tempx + ") ";
return (int)ExecuteInsertId(sql);
}
/// <summary>
/// 返回执行表
/// </summary>
/// <param name="SqlString"></param>
/// <returns></returns>
public DataTable ExecuteDataTable(string SqlString)
{
return ExecuteDataTable(SqlString, null);
}
/// <summary>
/// 执行sql返回DataTable
/// </summary>
/// <param name="SqlString">SQL语句</param>
/// <param name="parms">Sql参数</param>
/// <returns>DataTable</returns>
public DataTable ExecuteDataTable(string SqlString, MySqlParameter[] parms)
{
SleepOrGo();
bool frist = true;
Retry:
if (Conn == null || Conn.State != ConnectionState.Open)
ConnTo();
try
{
CmdIni();
cmd.CommandText = SqlString;
if (parms != null)
foreach (MySqlParameter pram in parms)
cmd.Parameters.Add(pram);
DataSet ds = new DataSet();
MySqlDataAdapter adapter = new MySqlDataAdapter();
adapter.SelectCommand = cmd;
adapter.Fill(ds);
return ds.Tables[0];
//DataTable dt = new DataTable();
//try
//{
// reader = cmd.ExecuteReader();
// dt.Load(reader);
//}
//catch
//{
// reader = cmd.ExecuteReader();
// dt = Read(ref reader);
//}
//return dt;
}
catch (Exception e)
{
if (frist)
{
frist = false;
ErrorDoing(e.Message);
goto Retry;
}
AddError(e.Message, SqlString);
return null;
}
finally
{
CloseReader();
IsRunning = false;
}
}
/// <summary>
/// 针对不同错误,执行不同的修正
/// </summary>
/// <param name="message"></param>
private void ErrorDoing(string message)
{
Message = message;
if (string.IsNullOrEmpty(message))
return;
if (message.Contains("Incorrect string value"))
return;
if (message.Contains("Connection must be valid and open"))
ConnTo();
if (message.Contains("There is already an open DataReader"))
{
Thread.Sleep(500);
ConnTo();
}
if (message.Contains("Fatal error encountered during command execution."))
ConnTo();
if (message.Contains(" StreamWriter ") || message.Contains("未将对象引用设置到对象的实例") || message.Contains("未将对象"))
ConnTo();
CloseReader();
Random ra = new Random(Guid.NewGuid().GetHashCode());
Thread.Sleep(ra.Next(200, 2000));
}
/// <summary>
/// 关闭读取线程
/// </summary>
private void CloseReader()
{
try
{
if (reader != null && !reader.IsClosed)
reader.Close();
cmd.Dispose();
//reader = null;
}
catch
{
}
}
/// <summary>
/// 返回执行行
/// </summary>
/// <param name="SqlString"></param>
/// <returns></returns>
public DataRow ExecuteDataTableRow(string SqlString)
{
return ExecuteDataTableRow(SqlString, null);
}
/// <summary>
/// 返回第一行
/// </summary>
/// <param name="SqlString"></param>
/// <returns></returns>
public DataRow ExecuteDataTableRow(string SqlString, MySqlParameter[] parms)
{
SleepOrGo();
bool frist = true;
Retry:
if (Conn == null || Conn.State != ConnectionState.Open)
ConnTo();
try
{
CmdIni();
cmd.CommandText = SqlString;
if (parms != null)
foreach (MySqlParameter pram in parms)
cmd.Parameters.Add(pram);
DataSet ds = new DataSet();
MySqlDataAdapter adapter = new MySqlDataAdapter();
adapter.SelectCommand = cmd;
adapter.Fill(ds);
DataTable dt = ds.Tables[0];
if (dt.Rows.Count > 0)
return dt.Rows[0];
}
catch (Exception e)
{
if (frist)
{
frist = false;
ErrorDoing(e.Message);
goto Retry;
}
AddError(e.Message, SqlString);
}
finally
{
CloseReader();
IsRunning = false;
}
return null;
}
/// <summary>
/// 返回第一个执行结果
/// </summary>
/// <param name="SqlString"></param>
/// <returns></returns>
public int ExecuteRowCount(string SqlString)
{
string f = ExecuteFirst(SqlString, null);
int c;
int.TryParse(f, out c);
return c;
}
public int ExecuteRowCount(string SqlString, MySqlParameter[] parms)
{
string f = ExecuteFirst(SqlString, parms);
int c;
int.TryParse(f, out c);
return c;
}
/// <summary>
/// 返回第一个执行结果
/// </summary>
/// <param name="SqlString"></param>
/// <returns></returns>
public string ExecuteFirst(string SqlString)
{
return ExecuteFirst(SqlString, null);
}
/// <summary>
/// 返回第一个执行结果
/// </summary>
/// <param name="SqlString"></param>
/// <returns></returns>
public int ExecuteFirstInt(string SqlString, MySqlParameter[] parms = null)
{
string id = ExecuteFirst(SqlString, parms);
int i;
int.TryParse(id, out i);
return i;
}
/// <summary>
/// 返回第一个执行结果
/// </summary>
/// <param name="SqlString"></param>
/// <returns></returns>
public decimal ExecuteFirstDecimal(string SqlString, MySqlParameter[] parms = null)
{
string id = ExecuteFirst(SqlString, parms);
decimal i;
decimal.TryParse(id, out i);
return i;
}
/// <summary>
/// 返回第一个值
/// </summary>
/// <param name="SqlString"></param>
/// <returns></returns>
public string ExecuteFirst(string SqlString, MySqlParameter[] parms)
{
SleepOrGo();
bool frist = true;
Retry:
if (Conn == null || Conn.State != ConnectionState.Open)
ConnTo();
try
{
CmdIni();
cmd.CommandText = SqlString;
if (parms != null)
foreach (MySqlParameter pram in parms)
cmd.Parameters.Add(pram);
reader = cmd.ExecuteReader();
if (reader.Read())
return reader[0].ToString();
return "";
}
catch (Exception e)
{
if (e.Message.Contains("Illegal mix of collations"))
return null;
if (frist)
{
frist = false;
ErrorDoing(e.Message);
goto Retry;
}
AddError(e.Message, SqlString);
}
finally
{
CloseReader();
IsRunning = false;
}
return null;
}
/// <summary>
/// 返回更改、插入或删除的行数
/// </summary>
/// <param name="SqlString"></param>
/// <param name="parms"></param>
/// <returns></returns>
public int ExecuteAffectedRows(string SqlString)
{
return ExecuteAffectedRows(SqlString, null);
}
/// <summary>
/// 返回更改、插入或删除的行数
/// </summary>
/// <param name="SqlString"></param>
/// <param name="parms"></param>
/// <returns></returns>
public int ExecuteAffectedRows(string SqlString, MySqlParameter[] parms)
{
SleepOrGo();
bool frist = true;
Retry:
if (Conn == null || Conn.State != ConnectionState.Open)
ConnTo();
try
{
CmdIni();
cmd.CommandText = SqlString;
if (parms != null)
foreach (MySqlParameter pram in parms)
cmd.Parameters.Add(pram);
reader = cmd.ExecuteReader();
if (reader.Read())
return reader.RecordsAffected;
return reader.RecordsAffected;
}
catch (Exception e)
{
if (e.Message.Contains("Illegal mix of collations"))
return 0;
if (frist)
{
frist = false;
ErrorDoing(e.Message);
goto Retry;
}
AddError(e.Message, SqlString);
}
finally
{
CloseReader();
IsRunning = false;
}
return 0;
}
/// <summary>
/// 返回插入ID
/// </summary>
/// <param name="SqlString"></param>
/// <returns></returns>
public long ExecuteInsertId(string SqlString)
{
return ExecuteInsertId(SqlString, null);
}
/// <summary>
/// 返回第一个值
/// </summary>
/// <param name="SqlString"></param>
/// <returns></returns>
public long ExecuteInsertId(string SqlString, MySqlParameter[] parms)
{
SleepOrGo();
bool frist = true;
Retry:
if (Conn == null || Conn.State != ConnectionState.Open)
ConnTo();
try
{
CmdIni();
cmd.CommandText = SqlString;
if (parms != null)
foreach (MySqlParameter pram in parms)
cmd.Parameters.Add(pram);
cmd.ExecuteNonQuery();
long id = cmd.LastInsertedId;
return id;
}
catch (Exception e)
{
if (e.Message.Contains(" for key 'PRIMARY'") && e.Message.Contains("Duplicate entry"))
return 0;
if (frist)
{
frist = false;
ErrorDoing(e.Message);
goto Retry;
}
AddError(e.Message, SqlString);
}
finally
{
CloseReader();
IsRunning = false;
}
return 0;
}
/// <summary>
/// 无返回
/// </summary>
/// <param name="SqlString"></param>
/// <returns></returns>
public bool ExecuteNonQuery(string SqlString)
{
return ExecuteNonQuery(SqlString, null);
}
/// <summary>
/// 只保留mysql可识别的字符串
/// </summary>
/// <param name="text"></param>
public string JustUtf8Words(string text)
{
JustUtf8Words(ref text);
return text;
}
/// <summary>
/// 只保留mysql可识别的字符串
/// </summary>
/// <param name="text"></param>
public void JustUtf8Words(ref string text)
{
if (string.IsNullOrEmpty(text))
return;
var cs = text.ToCharArray();
List<char> cc = new List<char>();
foreach (char c in cs)
{
if (c > 7814 && c < 8416 || c > 57096 && c < 59501 || c > 63707 && c < 64309 || c > 65505 || c < 0)
{
if (cc.Contains(c))
continue;
text = text.Replace(c.ToString(), "");
cc.Add(c);
}
}
}
/// <summary>
/// 执行无返回SQL语句
/// </summary>
/// <param name="SqlString">SQL语句</param>
/// <param name="parms">Sql参数</param>
///<returns>是否执行成功</returns>
public bool ExecuteNonQuery(string SqlString, MySqlParameter[] parms)
{
SleepOrGo();
bool frist = true;
Retry:
if (Conn == null || Conn.State != ConnectionState.Open)
ConnTo();
try
{
CmdIni();
cmd.CommandText = SqlString;
if (parms != null)
foreach (MySqlParameter pram in parms)
cmd.Parameters.Add(pram);
cmd.ExecuteNonQuery();
return true;
}
catch (Exception e)
{
if (e.Message.Contains("Illegal mix of collations") || e.Message.Contains("Incorrect string value")
|| e.Message.Contains(" for key 'PRIMARY'") && e.Message.Contains("Duplicate entry"))
return false;
if (frist)
{
frist = false;
ErrorDoing(e.Message);
goto Retry;
}
AddError(e.Message, SqlString);
return false;
}
finally
{
CloseReader();
IsRunning = false;
}
}
/// <summary>
/// 判断是否存在
/// </summary>
/// <param name="SqlString"></param>
/// <returns></returns>
public bool ExecuteExists(string SqlString)
{
return ExecuteExists(SqlString, null);
}
/// <summary>
/// 查询是否存在
/// </summary>
/// <param name="SqlString">SQL语句</param>
/// <param name="parms">SQL参数</param>
/// <returns>是否存在</returns>
public bool ExecuteExists(string SqlString, MySqlParameter[] parms)
{
SleepOrGo();
bool frist = true;
Retry:
if (Conn == null || Conn.State != ConnectionState.Open)
ConnTo();
try
{
CmdIni();
cmd.CommandText = SqlString;
if (parms != null)
foreach (MySqlParameter pram in parms)
cmd.Parameters.Add(pram);
reader = cmd.ExecuteReader();
if (reader.Read())
return true;
return false;
}
catch (Exception e)
{
if (frist)
{
frist = false;
ErrorDoing(e.Message);
goto Retry;
}
AddError(e.Message, SqlString);
return false;
}
finally
{
CloseReader();
IsRunning = false;
}
}
/// <summary>
/// 停止还是前进
/// </summary>
private void SleepOrGo()
{
int i = 0;
while (IsRunning && i < 300)
{
Thread.Sleep(100);
i++;
}
IsRunning = true;
}
/// <summary>
/// 初始化CMD
/// </summary>
private void CmdIni()
{
if (reader != null && !reader.IsClosed)
reader.Close();
if (cmd != null)
cmd.Dispose();
cmd = new MySqlCommand();
cmd.Connection = Conn;
cmd.CommandType = CommandType.Text;
cmd.CommandTimeout = TimeOut;
if (Transaction != null)
cmd.Transaction = Transaction;
}
/// <summary>
/// 连接数据库
/// </summary>
private void ConnTo()
{
Close();
try
{
Conn = new MySqlConnection(ConnString);
Conn.Open();
if (IsUseTrans)
this.Transaction = Conn.BeginTransaction();
}
catch (Exception e)
{
AddError(e.Message, ConnString);
}
}
/// <summary>
/// 错误信息
/// </summary>
/// <param name="message"></param>
/// <param name="sql"></param>
private void AddError(string message, string sql)
{
if (string.IsNullOrEmpty(message) || message.Contains("Illegal mix of collations"))
return;
ErrorDoing(message);
string errStr = "数据库连接错误:" + message + "\r\nSQL语句:" + sql;
try
{
if (!Directory.Exists("Log"))
{
Directory.CreateDirectory("Log");
}
File.AppendAllText("Log\\log-" + DateTime.Now.ToString("yyyyMMdd") + ".txt", errStr);
}
catch (Exception ex)
{
}
}
public void Commit()
{
if (Transaction != null)
Transaction.Commit();
}
public void RollBack()
{
if (Transaction != null)
Transaction.Rollback();
}
/// <summary>
/// 关闭数据库链接
/// </summary>
public void Close()
{
IsRunning = false;
try
{
if (Conn != null && Conn.State == ConnectionState.Open)
{
Conn.Close();
}
Conn = null;
try
{
if (reader != null && !reader.IsClosed)
reader.Close();
}
catch
{
}
reader = null;
try
{
if (Transaction != null)
Transaction.Dispose();
}
catch
{
}
Transaction = null;
}
catch
{
}
}
}
public class MysqlKeyValues
{
public List<MysqlKeyValue> List = new List<MysqlKeyValue>();
}
public class MysqlKeyValue
{
public MysqlKeyValue(string key, object value)
{
Key = key;
Value = value == null ? "" : MysqlUtils.ReplaceSqlSpecial(value.ToString());
}
public string Key = "";
public string Value;
}
/// <summary>
/// 根据连接串 key 提供 FreeSql IAdo(由框架 DI 注册的 keyed IFreeSql 提供)
/// </summary>
public static class AdoProvider
{
private static IServiceProvider _serviceProvider;
public static void SetServiceProvider(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
public static IAdo Get(string connKey)
{
if (string.IsNullOrEmpty(connKey))
connKey = "ConnKJD";
string key = connKey switch
{
"ConnKJD" => "KJDDB",
"ConnKJDBAK" => "KJDBAKDB",
_ => "KJDDB",
};
var fsql = _serviceProvider?.GetKeyedService<IFreeSql>(key);
if (fsql == null)
{
var fsql2 = _serviceProvider?.GetService<IFreeSql>();
if (fsql2 != null)
return fsql2.Ado;
throw new InvalidOperationException("IFreeSql not registered for key " + key);
}
return fsql.Ado;
}
}
}
@@ -0,0 +1,69 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace StoreHub.KJDWebService.Commons
{
public class RandomUtils
{
public static string WordBase = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz";
public static string NumberBase = "0123456789";
public static string WordNumberBase = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz01234567890123456789";
public static string SignWordBase = ".`~^*_| -#$%&?+";//".`~^*_| -#$%&?";
public static int GetId(int max)
{
return new Random(Guid.NewGuid().GetHashCode()).Next(0, max);
}
public static int GetId(int min, int max)
{
return new Random(Guid.NewGuid().GetHashCode()).Next(min, max);
}
public static string GetWord(int len)
{
StringBuilder s = new StringBuilder();
for (int i = 0; i < len; i++)
{
s.Append(WordBase[new Random(Guid.NewGuid().GetHashCode()).Next(WordBase.Length)]);
}
return s.ToString();
}
public static string GetNumber(int len)
{
StringBuilder s = new StringBuilder();
for (int i = 0; i < len; i++)
{
s.Append(NumberBase[new Random(Guid.NewGuid().GetHashCode()).Next(NumberBase.Length)]);
}
return s.ToString();
}
public static string GetWordNumber(int len)
{
StringBuilder s = new StringBuilder();
for (int i = 0; i < len; i++)
{
s.Append(WordNumberBase[new Random(Guid.NewGuid().GetHashCode()).Next(WordNumberBase.Length)]);
}
return s.ToString();
}
/// <summary>
/// 获取新的属性名称
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public static string GetNewProp(bool begin, string name)
{
char w = SignWordBase[new Random(Guid.NewGuid().GetHashCode()).Next(SignWordBase.Length)];
char add = SignWordBase[new Random(Guid.NewGuid().GetHashCode()).Next(SignWordBase.Length)];
if (begin)
name += "" + w + add;
else
name = "" + add + w + "" + name;
return name;
}
}
}
+762
View File
@@ -0,0 +1,762 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
namespace StoreHub.KJDWebService.Commons
{
public static class RegexUtils
{
/// <summary>
/// 返回正则对象所有结果
/// </summary>
/// <param name="HtmlString"></param>
/// <param name="RegexString"></param>
/// <returns></returns>
public static MatchCollection GetMatchRegex(string HtmlString, string RegexString)
{
if (HtmlString == null)
{
//LogSave.Add("匹配正则发生错误:原始字符串为空,正则:" + RegexString);
return null;
}
return Regex.Matches(HtmlString, RegexString, RegexOptions.IgnoreCase);
}
/// <summary>
/// 返回正则对象所有结果
/// </summary>
/// <param name="HtmlString"></param>
/// <param name="RegexString"></param>
/// <returns></returns>
public static MatchCollection GetMatchRegex(ref string HtmlString, string RegexString)
{
if (HtmlString == null)
{
//LogSave.Add("匹配正则发生错误:原始字符串为空,正则:" + RegexString);
return null;
}
return Regex.Matches(HtmlString, RegexString, RegexOptions.IgnoreCase);
}
/// <summary>
/// 返回单个正则分析结果
/// </summary>
/// <param name="HtmlString"></param>
/// <param name="RegexString"></param>
/// <returns></returns>
public static string GetMatchRegexString(ref string HtmlString, string RegexString)
{
if (HtmlString == null)
{
//LogSave.Add("匹配正则发生错误:原始字符串为空,正则:" + RegexString);
return null;
}
MatchCollection mc = Regex.Matches(HtmlString, RegexString, RegexOptions.IgnoreCase);
if (mc.Count > 0)
{
return mc[0].Groups[1].Value.ToString();
}
return null;
}
/// <summary>
/// 返回单个正则分析结果
/// </summary>
/// <param name="HtmlString"></param>
/// <param name="RegexString"></param>
/// <returns></returns>
public static string GetMatchMaxRegexString(ref string HtmlString, string RegexString)
{
if (HtmlString == null)
{
//LogSave.Add("匹配正则发生错误:原始字符串为空,正则:" + RegexString);
return null;
}
MatchCollection mc = Regex.Matches(HtmlString, RegexString, RegexOptions.IgnoreCase);
if (mc.Count > 0)
{
return mc[mc.Count - 1].Groups[1].Value.ToString();
}
return null;
}
/// <summary>
/// 返回匹配的数值
/// </summary>
/// <param name="HtmlString"></param>
/// <param name="RegexString"></param>
/// <returns></returns>
public static int GetMatchInt(ref string HtmlString, string RegexString)
{
string id = GetMatchRegexString(ref HtmlString, RegexString);
int i;
int.TryParse(id, out i);
return i;
}
/// <summary>
/// 返回单个正则分析结果
/// </summary>
/// <param name="HtmlString"></param>
/// <param name="RegexString"></param>
/// <returns></returns>
public static string GetMatchRegexString(string HtmlString, string RegexString)
{
if (HtmlString == null)
{
//LogSave.Add("匹配正则发生错误:原始字符串为空,正则:" + RegexString);
return null;
}
MatchCollection mc = Regex.Matches(HtmlString, RegexString, RegexOptions.IgnoreCase);
if (mc.Count > 0)
{
return mc[0].Groups[1].ToString();
}
return null;
}
/// <summary>
/// 是否存在匹配
/// </summary>
/// <param name="HtmlString"></param>
/// <param name="RegexString"></param>
/// <returns></returns>
public static bool MatchRegex(string HtmlString, string RegexString)
{
if (HtmlString == null)
{
//LogSave.Add("匹配正则发生错误:原始字符串为空,正则:" + RegexString);
return false;
}
return Regex.IsMatch(HtmlString, RegexString, RegexOptions.IgnoreCase);
}
/// <summary>
/// 根据正则删除表达式所匹配的内容
/// </summary>
/// <param name="HtmlString"></param>
/// <param name="RegexString"></param>
/// <returns></returns>
public static string Clear(string HtmlString, string RegexString)
{
if (HtmlString == null)
{
//LogSave.Add("匹配正则发生错误:原始字符串为空,正则:" + RegexString);
return null;
}
return Regex.Replace(HtmlString, RegexString, "", RegexOptions.IgnoreCase);
}
/// <summary>
/// 清除HTML代码
/// </summary>
/// <param name="HtmlString"></param>
/// <returns>返回文字内容</returns>
public static string ClearHtml(string HtmlString)
{
if (HtmlString == null)
{
//LogSave.Add("匹配正则发生错误:原始字符串为空");
return null;
}
return Regex.Replace(Regex.Replace(HtmlString,
@"(<head[\w\W]*?</head>|<script[\w\W]*?</script>|<style[\w\W]*?</style>|<!--[\w\W]*?-->)", ""), "(<[^>]*?>)", "").Trim();
}
/// <summary>
/// 清除HTML代码
/// </summary>
/// <param name="HtmlString"></param>
/// <returns>返回文字内容</returns>
public static string ClearHtml(ref string HtmlString)
{
if (HtmlString == null)
{
//LogSave.Add("匹配正则发生错误:原始字符串为空");
return null;
}
return Regex.Replace(Regex.Replace(HtmlString,
@"(<head[\w\W]*?</head>|<script[\w\W]*?</script>|<style[\w\W]*?</style>|<!--[\w\W]*?-->)", ""), "(<[^>]*?>)", "").Trim();
}
/// <summary>
/// 清除HTML代码
/// </summary>
/// <param name="HtmlString"></param>
/// <returns>返回文字内容</returns>
public static void ClearHtmlX(ref string HtmlString)
{
if (string.IsNullOrEmpty(HtmlString))
{
//LogSave.Add("匹配正则发生错误:原始字符串为空");
return;
}
HtmlString = Regex.Replace(Regex.Replace(HtmlString,
@"(<head[\w\W]*?</head>|<script[\w\W]*?</script>|<style[\w\W]*?</style>|<!--[\w\W]*?-->)", ""), "(<[^>]*?>)", "");
}
/// <summary>
/// 清除HTML代码A标签
/// </summary>
/// <param name="HtmlString"></param>
/// <returns>返回文字内容</returns>
public static string ClearA(string HtmlString)
{
if (HtmlString == null)
{
//LogSave.Add("匹配正则发生错误:原始字符串为空");
return null;
}
HtmlString = Regex.Replace(HtmlString, "(</?a[^>]*>)", "", RegexOptions.IgnoreCase);
return HtmlString.Trim();
}
/// <summary>
/// 去除空格和特殊空白
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public static string Trim(string text)
{
if (string.IsNullOrEmpty(text))
return "";
return text.Replace("\t", " ").Replace("\r\n", " ").Replace("\r", " ").Replace("\n", " ").Trim();
}
/// <summary>
/// 清除HTML代码A标签
/// </summary>
/// <param name="HtmlString"></param>
/// <returns>返回文字内容</returns>
public static string ClearTitle(string HtmlString)
{
if (HtmlString == null)
{
//LogSave.Add("匹配正则发生错误:原始字符串为空");
return null;
}
HtmlString = Regex.Replace(HtmlString, "(title=\"[^\"]*\")", "");
return HtmlString.Trim();
}
/// <summary>
/// 获取值
/// </summary>
/// <param name="html"></param>
/// <param name="reg"></param>
/// <returns></returns>
public static string GetValue(string html, string reg)
{
return GetMatchRegexString(html, "<" + reg + ">([^<]+)</" + reg + ">");
}
/// <summary>
/// 清理多余的HTML元素
/// </summary>
/// <param name="html"></param>
/// <returns></returns>
public static string ClearNone(string html)
{
if (string.IsNullOrEmpty(html))
return null;
if (html.Contains("\0") && html.IndexOf("\0") > 0)
html = html.Substring(0, html.IndexOf("\0"));
string h = Clear(html, @"(<\!doctype[^>]*?>)");
h = Clear(h, @"(<html[^>]*?>)");
h = Clear(h, @"(<head[\w\W]*?</head>)");
h = Clear(h, @"(<script[\w\W]*?</script>)");
h = Clear(h, @"(<style[\w\W]*?</style>)");
h = Clear(h, @"(<input[^>]*?>)");
h = Clear(h, @"(<!--[\w\W]*?-->)");
h = Clear(h, @"(<link[^>]*?>)");
h = Clear(h, @"(\s*alt\s*=[""'\s]*[^>]*?['""]+)");
h = Clear(h, @"(\s*style\s*=[""'\s]*[^>]*?['""]+)");
h = Clear(h, @"(\s*title\s*=[""'\s]*[^>]*?['""]+)");
h = Clear(h, @"(\s*id\s*=[""'\s]*[^>]*?['""]+)");
h = Clear(h, @"(\s*class\s*=[""'\s]*[^>]*?['""]+)");
h = Clear(h, @"(\s*align\s*=[""'\s]*[^>]*?['""]+)");
h = h.Replace("\r\n", " ");
h = h.Replace("\n", " ").Replace("\r", " ").Replace("\t", " ");
h = h.Replace(" ", " ");
h = h.Replace(" ", " ");
h = h.Replace(" ", " ");
h = h.Replace(" ", " ");
return h.Replace(" ", " ").Replace(" ", " ");
}
/// <summary>
/// 返回执行结果数
/// </summary>
/// <param name="html"></param>
/// <param name="regex"></param>
/// <returns></returns>
public static int GetRegexCount(string html, string regex)
{
if (html == null)
{
//LogSave.Add("匹配正则发生错误:原始字符串为空,正则:" + regex);
return 0;
}
return Regex.Matches(html, regex, RegexOptions.IgnoreCase).Count;
}
/// <summary>
/// 根据正则删除表达式所匹配的内容
/// </summary>
/// <param name="HtmlString"></param>
/// <param name="RegexString"></param>
/// <returns></returns>
public static string Relpace(string HtmlString, string RegexString, string NewString)
{
if (HtmlString == null)
return null;
return Regex.Replace(HtmlString, RegexString, NewString, RegexOptions.IgnoreCase);
}
/// <summary>
/// 根据正则删除表达式所匹配的内容
/// </summary>
/// <param name="HtmlString"></param>
/// <param name="RegexString"></param>
/// <returns></returns>
public static void Relpace(ref string HtmlString, string RegexString, string NewString)
{
if (HtmlString == null)
return;
HtmlString = Regex.Replace(HtmlString, RegexString, NewString, RegexOptions.IgnoreCase);
}
/// <summary>
/// 关键词在文本中出现的次数
/// </summary>
/// <param name="b"></param>
/// <param name="keyword"></param>
/// <returns></returns>
public static int GetStringCount(ref byte[] b, string keyword)
{
if (string.IsNullOrEmpty(keyword))
return 0;
int c = 0;
bool had;
byte[] b1 = Encoding.UTF8.GetBytes(keyword);
for (int i = 0; i < b.Length - b1.Length; i++)
{
had = false;
for (int j = 0; j < b1.Length; j++)
{
if (b[i + j] != b1[j])
{
had = true;
break;
}
}
if (had)
{
c++;
i += b1.Length - 1;
}
}
return c;
}
/// <summary>
/// 是否存在
/// </summary>
/// <param name="html"></param>
/// <param name="reg"></param>
/// <returns></returns>
public static bool Exists(string html, string reg)
{
if (string.IsNullOrEmpty(html) || string.IsNullOrEmpty(reg))
return false;
return new Regex(reg).IsMatch(html);
}
/// <summary>
/// 是否是数字
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static bool IsNumber(string str)
{
System.Text.RegularExpressions.Regex reg1 = new System.Text.RegularExpressions.Regex(@"^[0-9\.]+$");
return reg1.IsMatch(str);
}
/// <summary>
/// 是否是字母
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static bool IsChar(string str)
{
System.Text.RegularExpressions.Regex reg1 = new System.Text.RegularExpressions.Regex(@"^[A-Za-z]+$");
return reg1.IsMatch(str);
}
/// <summary>
/// 是否是字母
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static bool IsCharOrNumber(string str)
{
System.Text.RegularExpressions.Regex reg1 = new System.Text.RegularExpressions.Regex(@"^[A-Za-z0-9]+$");
return reg1.IsMatch(str);
}
/// <summary>
/// 是否是中文字符串列
/// </summary>
/// <param name="word"></param>
/// <returns></returns>
public static bool IsWordList(string word)
{
char[] xj = word.ToCharArray();
for (int j = 0; j < xj.Length; j++)
if (!IsWord(xj[j]))
return false;
return true;
}
/// <summary>
/// 是否是字符
/// </summary>
/// <param name="ascii"></param>
/// <returns></returns>
private static bool IsWord(int ascii)
{
if (ascii == 32 || ascii == 35) //空格
return true;
if (ascii < 58 && ascii > 47) //数字
return true;
if (ascii < 48 && ascii > 31) //符号
return true;
if (ascii < 91 && ascii > 64) //小写字母
return true;
if (ascii < 123 && ascii > 96) //大写字母
return true;
if (ascii < 40892 && ascii > 13311) //中文字符串
return true;
return false;
}
/// <summary>
/// 获取值
/// </summary>
/// <param name="html"></param>
/// <param name="reg"></param>
/// <returns></returns>
public static bool GetBoolValue(string html, string reg)
{
string temp = GetMatchRegexString(html, "<" + reg + ">([^<]+)</" + reg + ">");
if (!string.IsNullOrEmpty(temp) && (temp.ToLower() == "true" || temp == "1"))
return true;
return false;
}
/// <summary>
/// 获取值
/// </summary>
/// <param name="html"></param>
/// <param name="reg"></param>
/// <returns></returns>
public static int GetIntValue(string html, string reg)
{
string temp = GetMatchRegexString(html, "<" + reg + ">([^<]+)</" + reg + ">");
int i;
if (int.TryParse(temp, out i))
return i;
return 0;
}
/// <summary>
/// 获取值
/// </summary>
/// <param name="html"></param>
/// <param name="reg"></param>
/// <returns></returns>
public static long GetLongValue(string html, string reg)
{
string temp = GetMatchRegexString(html, "<" + reg + ">([^<]+)</" + reg + ">");
long i;
if (long.TryParse(temp, out i))
return i;
return 0;
}
/// <summary>
/// 获取值
/// </summary>
/// <param name="html"></param>
/// <param name="reg"></param>
/// <returns></returns>
public static double GetDoubleValue(string html, string reg)
{
string temp = GetMatchRegexString(html, "<" + reg + ">([^<]+)</" + reg + ">");
double i;
if (double.TryParse(temp, out i))
return i;
return 0;
}
/// <summary>
/// 获取值
/// </summary>
/// <param name="html"></param>
/// <param name="reg"></param>
/// <returns></returns>
public static DateTime GetDateValue(string html, string reg)
{
string temp = GetMatchRegexString(html, "<" + reg + ">([^<]+)</" + reg + ">");
DateTime i;
if (DateTime.TryParse(temp, out i))
return i;
return DateTime.MinValue;
}
/// <summary>
/// 获取值
/// </summary>
/// <param name="html"></param>
/// <param name="reg"></param>
/// <returns></returns>
public static decimal GetDecimalValue(string html, string reg)
{
string temp = GetMatchRegexString(html, "<" + reg + ">([^<]+)</" + reg + ">");
decimal i = 0;
if (decimal.TryParse(temp, out i))
return i;
return 0;
}
/// <summary>
/// 获取值
/// </summary>
/// <param name="html"></param>
/// <param name="reg"></param>
/// <returns></returns>
public static decimal GetDecimalJson(ref string html, string reg)
{
string temp = GetMatchRegexString(html, @"['""]" + reg + @"['""][\s]*:[\s]*['""]([^']+?)['""]");
if (string.IsNullOrEmpty(temp))
temp = GetMatchRegexString(html, @"['""]" + reg + @"['""][\s]*:[\s]*([\d-\.]+)");
decimal i = 0;
if (decimal.TryParse(temp, out i))
return i;
return 0;
}
/// <summary>
/// 获取值
/// </summary>
/// <param name="html"></param>
/// <param name="reg"></param>
/// <returns></returns>
public static int GetIntJson(ref string html, string reg)
{
string temp = GetMatchRegexString(html, @"['""]" + reg + @"['""][\s]*:[\s]*['""]([^']+?)['""]");
if (string.IsNullOrEmpty(temp))
temp = GetMatchRegexString(html, @"['""]" + reg + @"['""][\s]*:[\s]*([\d-]+)");
int i;
if (int.TryParse(temp, out i))
return i;
return 0;
}
/// <summary>
/// 时间戳转字符串时间
/// </summary>
/// <param name="html"></param>
/// <param name="reg"></param>
/// <returns></returns>
public static string GetIntTimeToString(ref string html, string reg)
{
return GetIntTimeToString(ref html, reg, 0);
}
/// <summary>
/// 时间戳转字符串时间
/// </summary>
/// <param name="html"></param>
/// <param name="reg"></param>
/// <param name="addTime">添加时间</param>
/// <returns></returns>
public static string GetIntTimeToString(ref string html, string reg, int addTime)
{
int time = GetIntJson(ref html, reg) + addTime;
DateTime dt = TimeUtils.StampToDateTime(time);
return dt.ToString("yyyy-MM-dd HH:mm:ss");
}
/// <summary>
/// 获取值
/// </summary>
/// <param name="html"></param>
/// <param name="reg"></param>
/// <returns></returns>
public static long GetLongJson(ref string html, string reg)
{
string temp = GetMatchRegexString(html, @"['""]" + reg + @"['""][\s]*:[\s]*['""]([^']+?)['""]");
if (string.IsNullOrEmpty(temp))
temp = GetMatchRegexString(html, @"['""]" + reg + @"['""][\s]*:[\s]*([\d]+)");
long i;
if (long.TryParse(temp, out i))
return i;
return 0;
}
/// <summary>
/// 获取值
/// </summary>
/// <param name="html"></param>
/// <param name="reg"></param>
/// <returns></returns>
public static string GetStringJson(ref string html, string reg)
{
string temp = GetMatchRegexString(html, @"[""]" + reg + @"[""][\s]*:[\s]*[""]([^""]+?)[""]");
if (temp == null)
temp = GetMatchRegexString(html, @"[""]" + reg + @"[""][\s]*:[\s]*[""]([^""]*?)[""]");
if (temp == null)
temp = GetMatchRegexString(html, @"[']" + reg + @"['][\s]*:[\s]*[']([^']*?)[']");
if (temp == null)
temp = GetMatchRegexString(html, @"['""]" + reg + @"['""][\s]*:[\s]*([\d]+)");
return temp;
}
/// <summary>
/// 获取值
/// </summary>
/// <param name="html"></param>
/// <param name="reg"></param>
/// <returns></returns>
public static string GetStringInput(ref string html, string reg)
{
string temp = GetMatchRegexString(html, @"<input [^>]*?name=['""]" + reg + @"[""'][^>]+?value=[""']([^>]+)[""'][^>]*>");
if (string.IsNullOrEmpty(temp))
temp = GetMatchRegexString(html, @"<input [^>]*?value=[""']([^>]+)[""'][^>]+?name=['""]" + reg + @"[""'][^>]*>");
return temp;
}
/// <summary>
/// 获取值
/// </summary>
/// <param name="html"></param>
/// <param name="key"></param>
/// <returns></returns>
public static string GetStringQuery(ref string queryString, string key, bool isGetJson = false)
{
List<string> strLst = queryString.Split('&').ToList();
var temp = strLst.FirstOrDefault(s => s.StartsWith(key + "="));
if (temp != null)
temp = ("&" + temp).Replace("&" + key + "=", "");
if (temp == null && isGetJson)
temp = GetStringJson(ref queryString, key);
//queryString = "&" + queryString;
//int nIndex = queryString.IndexOf("&" + key + "=");
//if (nIndex == -1)
// return null;
//string temp = queryString.Substring(nIndex).Replace("&" + key + "=", "");
//nIndex = temp.IndexOf('&');
//if (nIndex > -1)
// temp = temp.Substring(0, nIndex);
return temp;
}
public static string FliterHtmlTag(string htmlStr)
{
if (String.IsNullOrEmpty(htmlStr))
{
return "";
}
string regEx_style = "<style[^>]*?>[\\s\\S]*?<\\/style>"; //定义style的正则表达式
string regEx_script = "<script[^>]*?>[\\s\\S]*?<\\/script>"; //定义script的正则表达式
string regEx_html = "<[^>]+>"; //定义HTML标签的正则表达式
htmlStr = Regex.Replace(htmlStr, regEx_style, "");//删除css
htmlStr = Regex.Replace(htmlStr, regEx_script, "");//删除js
htmlStr = Regex.Replace(htmlStr, regEx_html, "");//删除html标记
htmlStr = Regex.Replace(htmlStr, "\\s*|\t|\r|\n", "");//去除tab、空格、空行
htmlStr = htmlStr.Replace("\"", "");//去除异常的引号
return htmlStr.Trim();
}
public static string GetOneJsonObjStrJson(ref string html, string reg)
{
return GetJsonObjStrJson(ref html, reg).FirstOrDefault();
}
public static List<string> GetJsonObjStrJson(ref string html, string reg, int level = 0)
{
List<string> rstLst = new List<string>();
if (html == null)
return rstLst;
string htmlTmp = html.Replace("\\{", "\\这里是正花括号占位符").Replace("\\}", "\\这里是反花括号占位符").Replace("\"" + reg + "\": {", "\"" + reg + "\":{");
retry:
string lvStr = "";
if (level == 1)
{
lvStr += "\"";
}
var index1 = htmlTmp.IndexOf("\"" + reg + "\":" + lvStr + "{");
if (index1 < 0)
return rstLst;
htmlTmp = htmlTmp.Substring(index1 + ("\"" + reg + "\":" + lvStr + "{").Length - 1);
// 括号计数
int braceNum = 0;
//string rst = "{";
//while (htmlTmp.Length > 0)
for (int i = 0; i < htmlTmp.Length; i++)
{
//rst += htmlTmp.Substring(0, 1);
//if (htmlTmp.StartsWith("{"))
// braceNum++;
//else if (htmlTmp.StartsWith("}"))
// braceNum--;
if (htmlTmp[i] == '{')
braceNum++;
else if (htmlTmp[i] == '}')
braceNum--;
//htmlTmp = htmlTmp.Substring(1);
if (braceNum == 0)
{
rstLst.Add(htmlTmp.Substring(0, i + 1).Replace("\\这里是正花括号占位符", "\\{").Replace("\\这里是反花括号占位符", "\\}"));
htmlTmp = htmlTmp.Substring(i + 1);
//rstLst.Add(rst.Replace("\\这里是正花括号占位符", "\\{").Replace("\\这里是反花括号占位符", "\\}"));
break;
}
// 循环完了还没结果返回空列表
if (i == htmlTmp.Length - 1)
return rstLst;
}
if (htmlTmp.Length > 0)
goto retry;
return rstLst;
}
public static List<string> GetJsonArrStrJson(ref string html, string reg)
{
List<string> rstLst = new List<string>();
if (html == null)
return rstLst;
string htmlTmp = html.Replace("\\[", "\\这里是正方括号占位符").Replace("\\]", "\\这里是反方括号占位符").Replace("\"" + reg + "\": [", "\"" + reg + "\":[");
retry:
var index1 = htmlTmp.IndexOf("\"" + reg + "\":[");
if (index1 < 0)
return rstLst;
htmlTmp = htmlTmp.Substring(index1 + ("\"" + reg + "\":[").Length);
// 括号计数
int braceNum = 1;
string rst = "[";
while (htmlTmp.Length > 0)
{
rst += htmlTmp.Substring(0, 1);
if (htmlTmp.StartsWith("["))
braceNum++;
else if (htmlTmp.StartsWith("]"))
braceNum--;
htmlTmp = htmlTmp.Substring(1);
if (braceNum == 0)
{
rstLst.Add(rst.Replace("\\这里是正方括号占位符", "\\[").Replace("\\这里是反方括号占位符", "\\]"));
break;
}
}
if (htmlTmp.Length > 0)
goto retry;
return rstLst;
}
}
}
+58
View File
@@ -0,0 +1,58 @@
using System;
using System.Collections.Generic;
using System.Linq;
namespace StoreHub.KJDWebService.Commons
{
public class TimeUtils
{
/// <summary>
/// 时间戳转为C#格式时间
/// </summary>
/// <param name="timeStamp"></param>
/// <returns></returns>
public static DateTime StampToDateTime(int timeStamp)
{
DateTime dateTimeStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
long lTime = long.Parse(timeStamp + "0000000");
TimeSpan toNow = new TimeSpan(lTime);
return dateTimeStart.Add(toNow);
}
/// <summary>
/// 时间戳转为C#格式时间
/// </summary>
/// <param name="timeStamp"></param>
/// <returns></returns>
public static DateTime StampMillisecondsToDateTime(long timeStamp)
{
DateTime dateTimeStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
long lTime = long.Parse(timeStamp + "0000");
TimeSpan toNow = new TimeSpan(lTime);
return dateTimeStart.Add(toNow);
}
/// <summary>
/// C#格式时间转换为Unix时间戳(秒)
/// </summary>
/// <param name="time"></param>
/// <returns></returns>
public static int DateTimeToTimestampSeconds(DateTime time)
{
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
return (int)(time - startTime).TotalSeconds;
}
/// <summary>
/// C#格式时间转换为Unix时间戳(毫秒)
/// </summary>
/// <param name="time"></param>
/// <returns></returns>
public static long DateTimeToTimestampMilliseconds(DateTime time)
{
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
return (long)(time - startTime).TotalMilliseconds;
}
}
}
@@ -0,0 +1,179 @@
using Asp.Versioning;
using Microsoft.AspNetCore.Mvc;
using StoreHub.KJDWebService.Services;
namespace StoreHub.KJDWebService.Controllers
{
[ApiController]
[ApiVersionNeutral]
[Route("bxx_price/[action]")]
public class BXXPriceController : BaseApiController
{
private readonly BXXPriceService _bXXPriceService;
public BXXPriceController(BXXPriceService bXXPriceService)
{
_bXXPriceService = bXXPriceService;
}
[AcceptVerbs("GET", "POST")]
public IActionResult get_price_list()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXPriceService.GetPriceList(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult add_price()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXPriceService.AddPrice(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult del_db_price()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXPriceService.DelDbPrice(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult mdy_db_price()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXPriceService.MdyDBPrice(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult mdy_purchase_price()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXPriceService.MdyPurchasePrice(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult add_purchase_price()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXPriceService.AddPurchasePrice(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult del_purchase_price()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXPriceService.DelPurchasePrice(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult get_purchase_price_list()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXPriceService.GetPurchasePriceList(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult add_ext_code_price()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXPriceService.AddExtCodePrice(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult get_ext_code_price_list()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXPriceService.GetExtCodePriceList(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult del_db_ext_code_price()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXPriceService.DelDbExtCodePrice(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult mdy_db_ext_code_price()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXPriceService.MdyDBExtCodePrice(jsontext);
return WriteJson(result);
}
}
}
@@ -0,0 +1,571 @@
using Asp.Versioning;
using Microsoft.AspNetCore.Mvc;
using StoreHub.KJDWebService.Services;
namespace StoreHub.KJDWebService.Controllers
{
[ApiController]
[ApiVersionNeutral]
[Route("bxx_product/[action]")]
public class BXXProductController : BaseApiController
{
private readonly BXXProductService _bXXProductService;
private readonly WXShopService _wXShopService;
public BXXProductController(BXXProductService bXXProductService, WXShopService wXShopService)
{
_bXXProductService = bXXProductService;
_wXShopService = wXShopService;
}
[AcceptVerbs("GET", "POST")]
public IActionResult get_product_spu_id_list()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXProductService.GetProductSpuIdLst(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult add_prod_down_sku()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXProductService.AddProdDownSku(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult get_prod_down_sku_lst_by_sku_codes()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXProductService.GetProdDownSkuLstBySkuCodes(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult get_product_list()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXProductService.GetProductList(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult get_product_detail_list()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXProductService.GetProductList(jsontext, true);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult get_product_list_random()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXProductService.GetProductListRandom(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult add_prod_wx_complate()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXProductService.AddProdWXComplate(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult get_prod_wx_complate_list()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXProductService.GetProdWXComplateList(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult get_sku_replace_img_list_random()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXProductService.GetSkuReplaceImgListRandom(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult add_product()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXProductService.AddProduct(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult mdy_product()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXProductService.MdyProduct(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult mdy_violation_prod()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXProductService.MdyViolationProd(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult mdy_best_sale_prod()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXProductService.MdyBestSaleProd(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult del_db_product()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXProductService.DelDbProd(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult mdy_db_product()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXProductService.MdyDBProduct(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult get_product_groups()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXProductService.GetProductGroups(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult add_product_groups()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXProductService.AddProductGroup(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult del_product_groups()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXProductService.DelProductGroup(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult get_product_notes()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXProductService.GetProductNotes(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult add_product_notes()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXProductService.AddProductNotes(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult del_product_notes()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXProductService.DelProductNotes(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult get_pdd_product_cates()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXProductService.GetProductMainCates(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult get_product_cates()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXProductService.GetProductCates(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult add_sku_img_replace()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXProductService.AddSkuImgReplace(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult mdy_sku_img_replace()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXProductService.MdySkuImgReplace(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult get_sku_img_replace_list()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXProductService.GetSkuImgReplaceList(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult get_sku_img_replace_detail_list()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXProductService.GetSkuImgReplaceList(jsontext, true);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult add_sku_img()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXProductService.AddSkuImg(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult get_wx_tokens()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _wXShopService.E57GetWxTokens(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult wx_api_get_all_cate()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXProductService.WxApiGetWxAllCate(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult wx_api_category_classify()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXProductService.WxApiCategoryClassify(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult wx_api_upload_image()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXProductService.WxApiUploadImage(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult add_jst_sku()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXProductService.AddJSTSku(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult mdy_jst_sku()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXProductService.MdyJSTSku(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult get_jst_sku_list()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXProductService.GetJSTSkuList(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult set_random_company_product_config()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXProductService.SetRandomCompanyProductConfig(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult get_random_company_product_config()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXProductService.GetRandomCompanyProductConfig(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult add_relation()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXProductService.AddRelation(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult get_relation()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXProductService.GetRelation(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult add_mdy_jst_product_ban()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXProductService.AddMdyJstProductBan(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult get_jst_product_coid_list()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXProductService.GetJstProductCoidList(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult get_jst_product_ban_platform_list()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXProductService.GetJstProductBanPlatformList(jsontext);
return WriteJson(result);
}
}
}
@@ -0,0 +1,179 @@
using Asp.Versioning;
using Microsoft.AspNetCore.Mvc;
using StoreHub.KJDWebService.Services;
namespace StoreHub.KJDWebService.Controllers
{
[ApiController]
[ApiVersionNeutral]
[Route("bxx_product_third/[action]")]
public class BXXProductThirdController : BaseApiController
{
private readonly BXXProductThirdService _bXXProductThirdService;
public BXXProductThirdController(BXXProductThirdService bXXProductThirdService)
{
_bXXProductThirdService = bXXProductThirdService;
}
[AcceptVerbs("GET", "POST")]
public IActionResult get_product_list()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXProductThirdService.GetProductList(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult get_product_detail_list()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXProductThirdService.GetProductList(jsontext, true);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult add_product()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXProductThirdService.AddProduct(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult del_db_product()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXProductThirdService.DelDbProd(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult mdy_product_category()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXProductThirdService.MdyProductCategory(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult add_user_select_product()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXProductThirdService.AddUserSelectProduct(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult mdy_user_select_product_status()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXProductThirdService.MdyUserSelectProductStatus(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult get_user_select_product_list()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXProductThirdService.GetUserSelectProductList(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult admin_get_user_select_product_list()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXProductThirdService.GetUserSelectProductList(jsontext, true);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult del_select_product()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXProductThirdService.DelSelectProd(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult set_select_product_sub_sa()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXProductThirdService.SetSelectProductSubSa(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult mdy_product_select_notes()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXProductThirdService.MdyProductSelectNotes(jsontext);
return WriteJson(result);
}
}
}
@@ -0,0 +1,337 @@
using Asp.Versioning;
using Microsoft.AspNetCore.Mvc;
using StoreHub.KJDWebService.Services;
namespace StoreHub.KJDWebService.Controllers
{
[ApiController]
[ApiVersionNeutral]
[Route("bxx_shop/[action]")]
public class BXXShopController : BaseApiController
{
private readonly BXXShopService _bXXShopService;
private readonly WXShopService _wXShopService;
public BXXShopController(BXXShopService bXXShopService, WXShopService wXShopService)
{
_bXXShopService = bXXShopService;
_wXShopService = wXShopService;
}
[AcceptVerbs("GET", "POST")]
public IActionResult get_pdd_client_info()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXShopService.GetPddClientInfo(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult get_shop_client_info()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXShopService.GetShopClientInfo(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult add_mdy_shop_client_info()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXShopService.AddMdyShopClientInfo(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult get_shop_list()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXShopService.GetShop(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult get_one_login_name_shop()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXShopService.GetOneLoginNameShop(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult add_shop()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXShopService.AddShop(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult del_shop()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXShopService.DelShop(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult mdy_shop()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXShopService.MdyShop(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult mdy_anti_content()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXShopService.MdyAntiContent(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult mdy_shop_cookie_and_login_status()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXShopService.MdyCookieAndLoginStatus(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult admin_get_shop_list()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXShopService.GetShop(jsontext, true);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult sub_sa_get_select_prod_shop()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXShopService.SubSaGetSelectProdShop(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult update_add_prod_remaining()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXShopService.UpdateAddProdRemaining(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult admin_mdy_shop()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXShopService.MdyShop(jsontext, true);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult admin_add_shop()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXShopService.AddShop(jsontext, true);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult admin_del_shop()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXShopService.DelShop(jsontext, true);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult set_shop_sub_sa()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXShopService.SetShopSubSa(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult e57_get_wx_tokens()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _wXShopService.E57GetWxTokens(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult e57_get_pdd_shop_token()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXShopService.E57GetPddShopToken(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult add_weidian_shop()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXShopService.AddWeiDianShop(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult mdy_weidian_shop()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXShopService.MdyWeiDianShop(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult mdy_weidian_shop_cookie()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXShopService.MdyWeiDianShopCookie(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult get_weidian_shop()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXShopService.GetWeiDianShop(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult del_weidian_shop()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXShopService.DelWeiDianShop(jsontext);
return WriteJson(result);
}
}
}
@@ -0,0 +1,252 @@
using Asp.Versioning;
using Microsoft.AspNetCore.Mvc;
using StoreHub.KJDWebService.Services;
namespace StoreHub.KJDWebService.Controllers
{
[ApiController]
[ApiVersionNeutral]
[Route("bxx_user/[action]")]
public class BXXUserController : BaseApiController
{
private readonly BXXUserService _bXXUserService;
public BXXUserController(BXXUserService bXXUserService)
{
_bXXUserService = bXXUserService;
}
[AcceptVerbs("GET", "POST")]
public IActionResult hello_world()
{
return Content("Hello World");
}
[AcceptVerbs("GET", "POST")]
public IActionResult user_login()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXUserService.CheckUserLogin(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult get_package_sign()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXUserService.GetPackageSign(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult change_password()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXUserService.ChangePassword(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult get_sub_user()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXUserService.GetSubUser(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult update_sub_user()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXUserService.UpdateSubUser(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult add_sub_user()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXUserService.AddSubUser(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult delete_user()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXUserService.DelUser(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult get_all_user()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXUserService.GetAllUser(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult update_user()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXUserService.UpdateUser(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult add_user()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXUserService.AddUser(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult update_scm121_cookie()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXUserService.UpdateScm121Cookie(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult get_scm121_cookie()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXUserService.GetScm121Cookie(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult add_buyer()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXUserService.AddBuyer(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult mdy_buyer()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXUserService.MdyBuyer(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult mdy_buyer_cookie()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXUserService.MdyBuyerCookie(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult get_buyer()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXUserService.GetBuyer(jsontext);
return WriteJson(result);
}
[AcceptVerbs("GET", "POST")]
public IActionResult del_buyer()
{
string jsontext = GetRequestJsonString();
var result = jsontext;
result = _bXXUserService.DelBuyer(jsontext);
return WriteJson(result);
}
}
}
@@ -0,0 +1,84 @@
using Asp.Versioning;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace StoreHub.KJDWebService.Controllers
{
/// <summary>
/// API 控制器基类:提供与旧 asmx 一致的请求读取(body JSON,为空回退 QueryString)
/// 与响应输出(text/html;charset=utf-8 原始 JSON 字符串)。
/// </summary>
[ApiController]
[ApiVersionNeutral]
public abstract class BaseApiController : ControllerBase
{
/// <summary>
/// 读取请求参数:先读 body,body 为空时回退 QueryString,统一转换为 key=value&amp;key=value 格式
/// (与旧 asmx 输入兼容,Manage 依赖 RegexUtils.GetStringQuery 解析 & 分隔的键值对)。
/// </summary>
protected string GetRequestJsonString()
{
Request.EnableBuffering();
string body = "";
using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8, true, 1024, true))
{
body = reader.ReadToEnd();
}
Request.Body.Position = 0;
if (string.IsNullOrEmpty(body))
{
var qs = Request.Query;
if (qs != null && qs.Count > 0)
{
var parts = new List<string>();
foreach (var key in qs.Keys)
{
parts.Add(key + "=" + qs[key].ToString());
}
return string.Join("&", parts);
}
return "";
}
// body 是 JSON 时转换为 key=value&key=value
string trimmed = body.Trim();
if (trimmed.StartsWith("{"))
{
try
{
var jObj = Newtonsoft.Json.Linq.JObject.Parse(trimmed);
var parts2 = new List<string>();
foreach (var prop in jObj.Properties())
{
parts2.Add(prop.Name + "=" + (prop.Value?.ToString() ?? ""));
}
return string.Join("&", parts2);
}
catch
{
// 不是合法 JSON,按原样返回
return body;
}
}
// 已是 key=value 或 form 格式
return body;
}
/// <summary>输出原始 JSON 字符串(与旧 Context.Response.Write 等价)</summary>
protected ContentResult WriteJson(string result)
{
return Content(result ?? "", "text/html;charset=utf-8", Encoding.UTF8);
}
}
}
Loaded 100 of 199 files, more files were not shown because too many files have changed in this diff. Show more